Kodewick
Start learning →
Project: a monthly report12 / 12

Project: a monthly report

Lesson 12 of 12 · Part 4 · Reports · about 25 minutes

Split a long query into steps in WITH: calendar → paid orders → basic monthly numbers → each person's first order month → new customers per month → build the report with a calendar LEFT JOIN → add LAG on the outside for month-over-month change. You can run each step on its own to check it.

You've been through a whole year of data, and the boss says: "Give me a monthly business report: how much we sold each month, how many people bought, how many new customers, how many returning ones, and how it compares with last month. And tell me what you see in it." This lesson ties together everything from the last 11 lessons to write that report.

First, work out what you need

In this step you don't write any code yet. First list every column of the report, and where each one comes from:

ColumnMeaningUses
monthThe month, all 12 with none missingLesson 10: generate a calendar with recursion
orders, salesNumber of paid orders, salesLesson 1: only count paid orders; lesson 2: group by month
buyersHow many people bought this monthLesson 2: COUNT(DISTINCT user_id)
new_buyersHow many people bought for the first time this monthLesson 8: first order month
returningReturning customers: buyers − new customersSubtraction
vs_lastHow much sales went up on last monthLesson 6: LAG

That's a lot for one query to work out, and written as one big lump it's hard to debug. The answer is to go step by step in WITH: each step does just one thing and gets a name.

Put in orderDrag, or use the arrows

Put these steps in an order that runs: later steps use the results of earlier ones.

  1. newbies AS (SELECT first_month AS month_start, COUNT(*) AS new_buyers FROM firsts GROUP BY first_month)
  2. WITH paid AS (SELECT user_id, amount, DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start FROM orders WHERE status = 'paid'),
  3. SELECT DATE_FORMAT(month_start, '%Y-%m') AS month, new_buyers FROM newbies ORDER BY month_start LIMIT 3;
  4. firsts AS (SELECT user_id, MIN(month_start) AS first_month FROM paid GROUP BY user_id),
Should print
month | new_buyers
2025-01 | 1
2025-03 | 6
2025-05 | 5

The calendar and the basic monthly numbers

In this step you write the first three steps: the calendar months, the paid orders paid (moving each date back to the 1st while you're at it), and the basic monthly numbers basics. Finally, LEFT JOIN the basics onto the calendar, so months with no orders get 0:

main.sql
1WITH RECURSIVE months AS (2    SELECT DATE('2025-01-01') AS month_start3    UNION ALL4    SELECT DATE_ADD(month_start, INTERVAL 1 MONTH)5    FROM months6    WHERE month_start < '2025-12-01'7),8paid AS (9    SELECT user_id, amount,10        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start11    FROM orders12    WHERE status = 'paid'13),14basics AS (15    SELECT month_start, COUNT(*) AS orders, SUM(amount) AS sales,16        COUNT(DISTINCT user_id) AS buyers17    FROM paid18    GROUP BY month_start19)20SELECT DATE_FORMAT(m.month_start, '%Y-%m') AS month,21    COALESCE(b.orders, 0) AS orders,22    COALESCE(b.sales, 0) AS sales,23    COALESCE(b.buyers, 0) AS buyers24FROM months AS m25LEFT JOIN basics AS b ON b.month_start = m.month_start26ORDER BY m.month_start;
Output
monthorderssalesbuyers
2025-011361
2025-02000
2025-0373667
2025-0421262
2025-051174310
2025-0653105
2025-071382012
2025-081162610
2025-091697713
2025-101278911
2025-1121104218
2025-121658815
12 rows

Note that WITH RECURSIVE is written only once, right at the start. The steps that aren't recursive, paid and basics, can still follow it.

Choose one

If you change LEFT JOIN to JOIN, which row goes missing?

New and returning customers

In this step you add the first order month from lesson 8: firsts is the month each person first bought, and newbies counts how many new customers each month has. Among this month's buyers, anyone who isn't new is a returning customer.

Exercise 1

New and returning customers in the last four months

Add new and returning customers to the report, for September to December only. Four columns: month, buyers, new_buyers and returning (buyers minus new customers), sorted by month.

It should print
monthbuyersnew_buyersreturning
2025-0913211
2025-101156
2025-1118216
2025-1215114
4 rows
exercise1.sql
1WITH RECURSIVE months AS (2    SELECT DATE('2025-01-01') AS month_start3    UNION ALL4    SELECT DATE_ADD(month_start, INTERVAL 1 MONTH)5    FROM months6    WHERE month_start < '2025-12-01'7),8paid AS (9    SELECT user_id, amount,10        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start11    FROM orders12    WHERE status = 'paid'13),14basics AS (15    SELECT month_start, COUNT(DISTINCT user_id) AS buyers16    FROM paid17    GROUP BY month_start18),19firsts AS (20    SELECT user_id, MIN(month_start) AS first_month21    FROM paid22    GROUP BY user_id23),24newbies AS (25    SELECT first_month AS month_start, COUNT(*) AS new_buyers26    FROM firsts27    GROUP BY first_month28)29SELECT DATE_FORMAT(m.month_start, '%Y-%m') AS month,30    COALESCE(b.buyers, 0) AS buyers31FROM months AS m32LEFT JOIN basics AS b ON b.month_start = m.month_start33WHERE m.month_start >= '2025-09-01'34ORDER BY m.month_start;
Output
Press Run or Ctrl+Enter

The whole report

In this step you put all the steps together. Every column is filled in first inside report, and then LAG on the outside works out the month-over-month change: once the calendar has filled the gaps, the previous row is always last month.

main.sql
1WITH RECURSIVE months AS (2    SELECT DATE('2025-01-01') AS month_start3    UNION ALL4    SELECT DATE_ADD(month_start, INTERVAL 1 MONTH)5    FROM months6    WHERE month_start < '2025-12-01'7),8paid AS (9    SELECT user_id, amount,10        DATE_SUB(order_date, INTERVAL DAY(order_date) - 1 DAY) AS month_start11    FROM orders12    WHERE status = 'paid'13),14basics AS (15    SELECT month_start, COUNT(*) AS orders, SUM(amount) AS sales,16        COUNT(DISTINCT user_id) AS buyers17    FROM paid18    GROUP BY month_start19),20firsts AS (21    SELECT user_id, MIN(month_start) AS first_month22    FROM paid23    GROUP BY user_id24),25newbies AS (26    SELECT first_month AS month_start, COUNT(*) AS new_buyers27    FROM firsts28    GROUP BY first_month29),30report AS (31    SELECT m.month_start,32        COALESCE(b.orders, 0) AS orders,33        COALESCE(b.sales, 0) AS sales,34        COALESCE(b.buyers, 0) AS buyers,35        COALESCE(n.new_buyers, 0) AS new_buyers36    FROM months AS m37    LEFT JOIN basics AS b ON b.month_start = m.month_start38    LEFT JOIN newbies AS n ON n.month_start = m.month_start39)40SELECT DATE_FORMAT(month_start, '%Y-%m') AS month,41    orders, sales, buyers, new_buyers,42    buyers - new_buyers AS returning,43    sales - LAG(sales) OVER (ORDER BY month_start) AS vs_last44FROM report45ORDER BY month_start;
Output
monthorderssalesbuyersnew_buyersreturningvs_last
2025-01136110NULL
2025-0200000-36
2025-037366761366
2025-042126202-240
2025-05117431055617
2025-065310523-433
2025-07138201257510
2025-08116261028-194
2025-091697713211351
2025-10127891156-188
2025-1121104218216253
2025-121658815114-454
12 rows

A complete monthly report: 12 rows, and you can explain how every column was worked out.

Choose one

What's March's vs_last?

Conclusions for the boss

This step is the last and most important part of data analysis: saying what the numbers mean. When you hand in the report, add a few sentences:

  1. Business is getting better, mostly thanks to returning customers. The second half of the year sold 4842, more than 3 times the 1581 of the first half. November had 18 buyers, and 16 of them were returning customers.
  2. Winning new customers has slowed down lately. There were 6 new customers in March and 5 each in May, July and October, but only 2 in November and 1 in December. Returning customers won't stay forever, so the shop needs a plan to bring in new ones.
  3. Don't jump to conclusions about December's drop. November had the big sales, and December's data only goes up to the 26th.

Also say how the numbers were counted and what's wrong with the data (the health check from lesson 1): only paid orders are counted, with cancelled, refunded and test orders left out; Elena may have signed up twice; and 2 users didn't fill in their city.

Choose one

Which of these can you not conclude from this report?

What you learned

  • Before writing a report, list every column and how it's worked out, then start.
  • Split a long query into steps in WITH. Each step does just one thing and can be run on its own to check it. WITH RECURSIVE only needs to be written once, at the very start.
  • Put the calendar on the left, LEFT JOIN all the numbers, fill in 0 with COALESCE, and work out LAG last.
  • New customers come from the first order month; buyers minus new customers are the returning customers.
  • Conclusions should start from the numbers and say how they were counted and what's wrong with the data. Don't write a guess as the reason.

You've finished the whole course! Next you can try the "SQL interview questions", where retention, login streaks and top N per group are all things this course has covered.

Finished this lesson?Mark it. Progress is saved in this browser, and you can undo it.
Practise what this lesson taught#021GROUP BY MONTH()Sales per monthStarter#023LAG()Change from last monthBasic#020AVG(n >= 2)Repeat buyersBasicAll 50 SQL problems →