Функции аналитического окна - ваш лучший выбор - см. Ответ Виньеша Кумара А., который я проголосовал.
Если ваш SQL-код не имеет ROW_NUMBER()
или RANK()
, вы можете выполнить то же самое с помощью следующегоприсоединяется.
-- this can be problematic if there's multiple prices for the same max ChangeDate
SELECT
a.ID
, a.ProductID
, a.ChangeDate
, a.PriceOld
, a.PriceNew
FROM table a
JOIN (SELECT ProductID, max(ChangeDate) max_ChangeDate
FROM TABLE
GROUP BY ProductID) b
ON b.ProductID = a.ProductID
AND b.max_ChangeDate = a.ChangeDate
-- if IDs are monotonically increasing with time, you can exploit the following. This is better than directly using ChangeDate -- no collisions.
SELECT
a.ID
, a.ProductID
, a.ChangeDate
, a.PriceOld
, a.PriceNew
FROM table a
JOIN (SELECT ProductID, max(ID) max_ID
FROM TABLE
GROUP BY ProductID) b
ON b.ProductID = a.ProductID
AND b.max_ID = a.ID