Optimize a query or suggest LINQ equivalent

Viewed 249

I have a table containing columns date_trans, time_trans, price. After select query, I want to add a new column "Count" which will be calculated as the consecutive equal values of price column and the previous rows having consecutive equal prices will be removed from the final result. See the expected output:

date_trans  time_trans  price   **Count**    
2011-02-22  09:39:59    58.02   1
2011-02-22  09:40:03    58.1    *ROW WILL BE REMOVED
2011-02-22  09:40:07    58.1    *ROW WILL BE REMOVED
2011-02-22  09:40:08    58.1    3
2011-02-22  09:40:10    58.15   1
2011-02-22  09:40:10    58.1    *ROW WILL BE REMOVED
2011-02-22  09:40:14    58.1    2
2011-02-22  09:40:24    58.15   1
2011-02-22  09:40:24    58.18   *ROW WILL BE REMOVED
2011-02-22  09:40:24    58.18   *ROW WILL BE REMOVED
2011-02-22  09:40:24    58.18   3
2011-02-22  09:40:24    58.15   1

Please suggest a sql query or LINQ expression to select from the table

Currently, I can do it be a select query and looping through all the selected rows but when selecting millions of rows it takes hours.

My current code:

    string query = @"SELECT date_trans, time_trans,  price
                            FROM tbl_data 
                         WHERE date_trans BETWEEN '2011-02-22' AND '2011-10-21'
                        AND time_trans BETWEEN '09:30:00' AND '16:00:00'";

            DataTable dt = oUtil.GetDataTable(query);

            DataColumn col = new DataColumn("Count", typeof(int));
            dt.Columns.Add(col);

            int priceCount = 1;
            for (int count = 0; count < dt.Rows.Count; count++)
            {
                double price = Convert.ToDouble(dt.Rows[count]["price"]);
                double priceNext = (count == dt.Rows.Count - 1) ? 0 : Convert.ToDouble(dt.Rows[count + 1]["price"]);
                if (price == priceNext)
                {
                    priceCount++;
                    dt.Rows.RemoveAt(count);
                    count--;
                }
                else
                {
                    dt.Rows[count]["Count"] = priceCount;
                    priceCount = 1;
                }
            }
1 Answers
Related