SQL · Level 3 Project

Project: SQL Monthly Growth Report

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

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;

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.

Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.

orders 6 rows
idINTEGERcreated_atTEXTstatusTEXTtotalINTEGER
12024-01-05 10:00paid100
22024-01-20 10:00paid100
32024-02-03 10:00paid250
42024-02-10 10:00refunded999
52024-03-01 10:00paid150
62024-03-31 23:00paid50
solution.sql
Test Suites Pending
Output