For SQL Server 2012+:
Du kan bruge LAG
funktion.
Her er et eksempel for at finde den tidligere modtagne værdi, så ville de andre selvfølgelig være ret ens.
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
Ellers
Jeg var allerede godt i gang med dette svar, før du kommenterede tilbage, så jeg gik bare med det.
Du skal bruge en CTE og forbinde den med sig selv ved den rækkenummerforskydning, du leder efter.
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