BBampaa

Lessons › SQL › Chapter 6: Window Functions

SQL lesson

Comparison vs previous period

Last level, LAG put last month's revenue next to this month's. Now subtract them: revenue - LAG(revenue) is the change. Above zero, it went up. Below zero, it went down. Divide the change by last month to get growth: 0.18 means 18% up.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

Did it go up or down?

SELECT month,
       revenue,
       revenue - LAG(revenue) OVER (ORDER BY month) AS change,
       ROUND((revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month), 2) AS growth
FROM monthly_sales

Result:

monthrevenuechangegrowth
2024-0112400.5
2024-0211800.25-600.25-0.05
2024-0313900.02099.750.18
2024-0415200.751300.750.09
2024-0514600.4-600.35-0.04

Step by step

  1. Last month's revenue, from the row above, like the last level.
    SELECT month, revenue, revenue - LAG(revenue) OVER (ORDER BY month) AS change FROM monthly_sales
  2. This month minus last month. Below zero means it went down.
    SELECT month, revenue, revenue - LAG(revenue) OVER (ORDER BY month) AS change FROM monthly_sales
  3. The change as a share of last month. 0.18 means 18% up.
    SELECT month, revenue, ROUND((revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month), 2) AS growth FROM monthly_sales

Practice

Try each one in your head first, then open the answer.

1. Using monthly_sales, show month, revenue and how much revenue changed from the month before. Name it change.
SELECT month, revenue, revenue - LAG(revenue) OVER (ORDER BY month) AS change FROM monthly_sales
2. Now show growth on the month before as a decimal, rounded to 2 places. Name it growth.
SELECT month, revenue, ROUND((revenue - LAG(revenue) OVER (ORDER BY month)) / LAG(revenue) OVER (ORDER BY month), 2) AS growth FROM monthly_sales
3. Using weekly_sales, show week_start, orders and how many more (or fewer) orders there were than the week before. Name it change.
SELECT week_start, orders, orders - LAG(orders) OVER (ORDER BY week_start) AS change FROM weekly_sales
4. Using yearly_sales, show year, revenue and the growth on the year before as a decimal, rounded to 2 places. Name it growth.
SELECT year, revenue, ROUND((revenue - LAG(revenue) OVER (ORDER BY year)) / LAG(revenue) OVER (ORDER BY year), 2) AS growth FROM yearly_sales
5. Using store_monthly, show store_id, month, revenue and the change from that store's month before. Name it change.
SELECT store_id, month, revenue, revenue - LAG(revenue) OVER (PARTITION BY store_id ORDER BY month) AS change FROM store_monthly

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed