SQL Server 2012 以降の場合:
LAG
を使用できます
関数。
以下は、以前に受け取った値を見つける例です。もちろん、他の値もまったく同じです。
SELECT TOP 5
ReceivedYTD,
InvoicedYTD,
OrderedYTD,
YearReported,
WeekReported,
-- Relevant part
LAG(ReceivedYTD)
OVER (ORDER BY YearReported DESC, WeekReported DESC) AS PreviousReceivedYTD
-- End relevant part
FROM Products
WHERE ProductId = @ProductId
ORDER BY YearReported DESC,
WeekReported DESC
それ以外
あなたがコメントする前に、私はすでにこの回答に夢中だったので、それで行きました.
CTE を使用し、探している行番号のオフセットで結合する必要があります。
WITH CTE AS (
SELECT TOP 5
RowNumber = ROW_NUMBER() OVER (ORDER BY YearReported DESC, WeekReported DESC)
ReceivedYTD,
InvoicedYTD,
OrderedYTD,
YearReported,
WeekReported,
FROM Products
WHERE ProductId = @ProductId
ORDER BY YearReported DESC,
WeekReported DESC
)
SELECT CTE.ReceivedYTD,
CTE.InvoicedYTD,
CTE.OrderedYTD,
CTE.YearReported,
CTE.WeekReported,
PreviousRow.ReceivedYTD AS PreviousReceivedYTD
FROM CTE
LEFT OUTER JOIN CTE PreviousRow ON CTE.RowNumber - 1 = PreviousRow.RowNumber