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
Ini adalah cara yang harus Anda lakukan di SQL Server. Itu membuat "last/first/max/min/greatest-n-per grup" semudah pie.
PARTITION BY
kata kunci di sini sama dengan GROUP BY
Anda pernyataan, dan ORDER BY
di sini akan diterjemahkan ke dalam MAX
fungsi agregat yang Anda gunakan di MySQL
Menggunakan ini akan memungkinkan Anda untuk melakukan beberapa hal mewah seperti:
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