我有一個包含視圖,顯示供應點抄表它具有以下列的SQL Server 2000數據庫:是否有可能在SQL Server 2000中執行返回整行的GROUP BY?
- rh_sp_number <- the number of the supply point
- rh_... <- a bunch of other columns pertaining to that specific reading row
- rh_end_date <- a `DateTime`field that holds the date of the reading
每個SupplyPoint可以有0..N讀數。我需要爲任何給定的SupplyPoint提取上次提交的行。我想用一個查詢到數據庫來完成此操作。
我需要做這樣的事情:
var q = db.READINGS_HISTORY.Where(rh => ids.Contains(rh.rh_sp_number))
.GroupBy(rh => rh.rh_sp_number, rh => rh,
(key, values) => values.OrderByDescending(rh => rh.rh_end_date).FirstOrDefault())
.ToList();
在人類語言中,我需要選擇各組的最後一行,並返回該行。運行此查詢(或者說我能想到的任何其他組合)會導致這樣的:
此查詢的執行需要APPLY運算符,這是 在SQL Server版本不支持早於SQL Server的 2005年
我需要在SQL Server來完成這個2000
這並不一定是一個「分組依據」表達;任何將返回給定密鑰的最大行將做。
我的解決辦法:
基於阿倫斯答案,我結束了與此查詢,做我需要什麼(一個警告,但業務規則刪除它形成方程對我來說)。
的警告:如果對於同一SupplyPoints的SQL Server將決定選擇
var hists = db.READINGS_HISTORY.Where(rh => ids.Contains(rh.rh_sp_number))
.GroupBy(rh => rh.rh_sp_number, rh => rh,
(key, values) => new { key, date = values.Max(rh => rh.rh_end_date) })
.Join(db.READINGS_HISTORY, g => new { sp = g.key, date = g.date },
rh2 => new { sp = rh2.rh_sp_number, date = rh2.rh_end_date }, (g, rh) => rh)
.Select(rh => new LastReading
{
//omitted..
}).ToList();
我不能真正閱讀第一個代碼塊。你可以顯示錶格結構,確定關鍵值,一些樣品數據和所需的結果嗎? –
我添加了一些更多的信息。 –
你可以用LINQ調用一個存儲過程而不是所有那個mumbo-jumbo嗎?我確信有一種方法可以讓LINQ在我的答案中形成查詢,但是我懷疑如果使用該代碼創建存儲過程並調用它,那麼它的工作量會少很多。或者一個視圖可能更容易從LINQ中引用? –