T-SQL reference › LAG and LEAD
LAG and LEAD in SQL Server: the previous row
LAG looks at the previous row in the order you set. LEAD looks forward. That is month-over-month without joining the table to itself.
Month-over-month revenue
WITH m AS (
SELECT CONVERT(char(7), order_date, 120) AS month,
SUM(total_amount) AS revenue
FROM Orders
GROUP BY CONVERT(char(7), order_date, 120)
)
SELECT month, revenue,
LAG(revenue) OVER (ORDER BY month) AS prev_month,
revenue - LAG(revenue) OVER (ORDER BY month) AS change
FROM m
ORDER BY month;
The first month has no previous row, so LAG is NULL. Wrap it in ISNULL if the sheet cannot stand a blank.
Try it on Harbour & Co
Amy Nair (Finance Lead) needs this now: “Monthly revenue with the change from the month before. Leave out cancelled orders.” Write the query, run it, send the results. On the paid plan.
Take the ticket →Learn it on a real ticket
Monday is free on WorkSQL. A colleague’s ticket lands, you write the T-SQL, we mark it. No videos. Five minutes.
Clock in free See Monday’s tickets