I have a situation where I need select the current and previous order amount in a single row using a select statement.
Order Table:
Customer Id
OrderId
OrderDate
OrderAmount
Current Select Statement:
SELECT o.OrderId, o.OrderDate, o.OrderAmount, po.OrderAmount
FROM Order o
LEFT JOIN (
SELECT TOP(1) so.OrderAmount
FROM Order so
WHERE so.CustomerId = o.CustomerId and so.OrderId <> o.OrderId
ORDER BY so.OrderDate DESC
) po
The problem is that the “where” clause in the sub query is not allowed. Is there another method for getting this information.
This is actually a simplification of a more complex select (for a view) that requires data for financial reports for the current and previous reporting period.
You would need
OUTER APPLYhere.Your
WHEREclause doesn’t look right though. I’ve assumeOrderDateis unique below in being able to determine “previous” row.But you may well be better off left joining on
ROW_NUMBER