我有一个包含列 date_trans、time_trans、price 的表。在选择查询之后,我想添加一个新列“计数”,它将计算为价格列的连续相等值,并且先前具有连续相等价格的行将从最终结果中删除。查看预期输出:
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
请建议从表中选择的 sql 查询或 LINQ 表达式
目前,我可以将其作为一个选择查询并循环遍历所有选定的行,但是在选择数百万行时需要几个小时。
我当前的代码:
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;
}
}