Overview
Build a month-by-month growth report: total paid revenue per month in a CTE, compare each month with the one before using LAG, and compute the percent.
- CTE, then window function
- LAG over monthly totals
- Growth = 100.0 * (now - before) / before
Short Course
Analysts build reports in steps: a CTE for the monthly totals, then a window
function to compare months. Trap: growth is (now - before) / before, and
with integer columns that division truncates to 0. Write 100.0 * first.
WITH monthly AS (
SELECT substr(day, 1, 7) AS month, SUM(visits) AS visits
FROM traffic
GROUP BY month
)
SELECT month, visits,
LAG(visits) OVER (ORDER BY month) AS previous
FROM monthly;
Task
For each month of paid orders, return the month ('2024-03'), its revenue
and its growth from the previous month in percent, rounded to 1 decimal (NULL
for the first month), ordered by month. In the database below, February grew
25% over January.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | created_atTEXT | statusTEXT | totalINTEGER |
|---|---|---|---|
| 1 | 2024-01-05 10:00 | paid | 100 |
| 2 | 2024-01-20 10:00 | paid | 100 |
| 3 | 2024-02-03 10:00 | paid | 250 |
| 4 | 2024-02-10 10:00 | refunded | 999 |
| 5 | 2024-03-01 10:00 | paid | 150 |
| 6 | 2024-03-31 23:00 | paid | 50 |
Test Suites
Pending
Next
Output