WITH Data AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) AS Row_Number,
ID,
AverageValue
FROM Table
)
SELECT * FROM Data WHERE Row_Number = 1
這是您應該在SQL Server中執行此操作的方式。它使得「最後/第一/最大/最小/最大 - 每組」最簡單。這裏
PARTITION BY
關鍵字等於你GROUP BY
聲明,這裏的ORDER BY
會轉化爲你的MySQL
使用使用這將使你做一些花哨的東西,如MAX
聚合函數:
WITH Data AS
(
SELECT ROW_NUMBER() OVER (PARTITION BY ID ORDER BY Date DESC) AS Row_Number,
ID,
AverageValue
FROM Table
)
SELECT Newest.ID,
Newest.AverageValue,
(Newest.AverageValue - Next_Newest.AverageValue) AS AverageValue_Change,
Newest.Date
FROM Data Newest
LEFT OUTER JOIN Data Next_Newest
ON Newest.Row_Number+1 = Next_Newest.Row_Number
AND Newest.ID = Next_Newest.ID
WHERE Newest.Row_Number=1
你在'ID'之前有一個額外的支架我認爲... – 2012-01-05 11:54:02
謝謝,但我認爲,這並不意味着我可以在SQL Server中做到以上幾點?給我的印象是嵌套連接的整個語法是不同的? – mezamorphic 2012-01-05 11:55:06
@ user1107474:爲什麼不試試呢?它應該運行得非常好。 – 2012-01-05 11:56:10