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 →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| month | revenue | change | growth |
|---|---|---|---|
| 2024-01 | 12400.5 | ||
| 2024-02 | 11800.25 | -600.25 | -0.05 |
| 2024-03 | 13900.0 | 2099.75 | 0.18 |
| 2024-04 | 15200.75 | 1300.75 | 0.09 |
| 2024-05 | 14600.4 | -600.35 | -0.04 |
Step by step
- 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 - 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 - 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
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_sales2. 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_sales3. 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_sales4. 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_sales5. 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_monthlyLearn 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 →