我有一個表,包含列date_trans,time_trans,價格。選擇查詢後,我想添加一個新的列「計數」,它將被計算爲價格列的連續相等值,並且具有連續相等價格的前一行將從最終結果中移除。看到預期的輸出:優化查詢或建議LINQ等效
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;
}
}
我認爲在SQL中可以使用分析函數。現在已經很晚了,所以我的大腦現在不能完全處理,但是當我休息時,我會回來看看你是否還需要一個答案。但我認爲你應該首先看看[這個答案](http://stackoverflow.com/questions/7854854/getting-all-consecutive-rows-differing-by-certain-value)以及它如何使用分析函數。 – Ally 2012-07-22 03:35:38