Project: Sales Report

Updated · 11 min read
mediumPostgreSQL 18sqlprojectreportingwindow-functionsrollupctepractice

In this project, you build the report a small business owner actually reads each month: how much came in, how that compares with last month, what sold best, and who still owes money. Srihitha runs the tutoring program's books, and every month she copies numbers from the Fee Tracker into a spreadsheet by hand. Your job is to replace that with a set of SQL queries she can run any time and trust. The report has five parts, each a query that builds on skills from earlier lessons; at the end, you'll put the parts together and review the set the way a teammate would. All of it runs on the Fee Tracker as it is.

In One Minute

  • Part 1: totals per month, with no missing months.
  • Part 2: month-over-month change, with lag().
  • Part 3: courses ranked by fees collected, with RANK().
  • Part 4: subtotals by technology and course, with ROLLUP.
  • Part 5: who still owes money for active enrollments.
  • Review: consistent names, money to the cent, clear sorting, NULL handled, numbers that add up.

The Brief

Srihitha's request, in her words: "Each month I need to know: how much we collected, whether that's up or down from the month before, which courses bring in the most, the totals by technology, and who still owes us. The numbers have to match: if the course totals don't add up to the month totals, I can't use them."

That last sentence is the most important requirement. A report whose parts disagree is worse than no report. We'll check that every total in the report adds up to the same grand total.

Part 1: Totals per Month, Without Gaps

A monthly report must show every month, even one with no payments. Grouping the payments alone would skip September 2025, when nobody paid. A calendar of months, made with generate_series, fills the gap (Date Functions):

SQL▶ Try it
WITH months AS (
  SELECT generate_series(DATE '2025-08-01', DATE '2026-01-01', INTERVAL '1 month')::date AS month_start
)
SELECT to_char(m.month_start, 'YYYY-MM')       AS month,
       count(p.payment_id)                     AS payments,
       coalesce(sum(p.amount_usd), 0.00)       AS collected_usd
FROM months AS m
LEFT JOIN payments AS p
  ON p.paid_on >= m.month_start
 AND p.paid_on <  m.month_start + INTERVAL '1 month'
GROUP BY m.month_start
ORDER BY m.month_start;
Output
  month  | payments | collected_usd
---------+----------+---------------
 2025-08 |        1 |        450.00
 2025-09 |        0 |          0.00
 2025-10 |        1 |        250.00
 2025-11 |        1 |        225.00
 2025-12 |        3 |       1025.00
 2026-01 |        1 |        200.00
(6 rows)

Explanation: The CTE lists the first day of each month from August 2025 to January 2026. The LEFT JOIN keeps every month, attaching the payments whose paid_on falls inside it; the range >= start AND < start + 1 month catches every day of the month without worrying about how many days it has. September shows 0 payments and 0.00 instead of vanishing. coalesce(..., 0.00) turns the empty month's NULL sum into zero (NULL Functions).

Part 2: Month-Over-Month Change

lag() reads a value from the previous row, so each month can be compared with the one before (Window Functions):

SQL▶ Try it
WITH months AS (
  SELECT generate_series(DATE '2025-08-01', DATE '2026-01-01', INTERVAL '1 month')::date AS month_start
),
monthly AS (
  SELECT m.month_start, coalesce(sum(p.amount_usd), 0.00) AS collected_usd
  FROM months AS m
  LEFT JOIN payments AS p
    ON p.paid_on >= m.month_start AND p.paid_on < m.month_start + INTERVAL '1 month'
  GROUP BY m.month_start
)
SELECT to_char(month_start, 'YYYY-MM') AS month,
       collected_usd,
       collected_usd - lag(collected_usd) OVER (ORDER BY month_start) AS change_usd,
       round(100.0 * (collected_usd - lag(collected_usd) OVER (ORDER BY month_start))
             / NULLIF(lag(collected_usd) OVER (ORDER BY month_start), 0), 1) AS change_pct
FROM monthly
ORDER BY month_start;
Output
  month  | collected_usd | change_usd | change_pct
---------+---------------+------------+------------
 2025-08 |        450.00 |       NULL |       NULL
 2025-09 |          0.00 |    -450.00 |     -100.0
 2025-10 |        250.00 |     250.00 |       NULL
 2025-11 |        225.00 |     -25.00 |      -10.0
 2025-12 |       1025.00 |     800.00 |      355.6
 2026-01 |        200.00 |    -825.00 |      -80.5
(6 rows)

Explanation: August has no previous month, so its change is NULL, which is correct: "no comparison", not "no change". October's percentage is also NULL, because September collected 0.00 and a percentage change from zero has no meaning. NULLIF(previous, 0) turns that zero into NULL, so the division gives NULL instead of a division-by-zero error. December was the best month, up 355.6% on November.

Every month shown, even an empty one, with the change from the month before

Part 3: Courses Ranked

Rank the courses by fees collected, including any course that has collected nothing yet (Ranking Functions):

SQL▶ Try it
SELECT c.title,
       count(p.payment_id)                 AS payments,
       coalesce(sum(p.amount_usd), 0.00)   AS collected_usd,
       RANK() OVER (ORDER BY coalesce(sum(p.amount_usd), 0.00) DESC) AS rank
FROM courses AS c
LEFT JOIN payments AS p ON p.course_id = c.course_id
GROUP BY c.course_id, c.title
ORDER BY rank, c.title;
Output
       title       | payments | collected_usd | rank
-------------------+----------+---------------+------
 Java Collections  |        1 |        550.00 |    1
 Java OOP          |        2 |        500.00 |    2
 Java Basics       |        1 |        450.00 |    3
 JavaScript Basics |        2 |        450.00 |    3
 SQL Basics        |        1 |        200.00 |    5
 Git Basics        |        0 |          0.00 |    6
(6 rows)

Explanation: Java Collections ranks first with one $550.00 payment, just ahead of Java OOP's two payments of $250.00. Java Basics and JavaScript Basics tie at $450.00, so RANK() gives both rank 3 and skips 4: SQL Basics is fifth. Git Basics, with no enrollments and no payments, appears with 0.00 thanks to the LEFT JOIN, last on the list.

Part 4: Subtotals by Technology

ROLLUP adds a subtotal for each technology and a grand total in the same result (ROLLUP, CUBE and GROUPING SETS):

SQL▶ Try it
SELECT CASE WHEN GROUPING(c.technology) = 1 THEN 'All technologies'
            ELSE c.technology END                         AS technology,
       CASE WHEN GROUPING(c.title) = 1 THEN 'Subtotal'
            ELSE c.title END                              AS course,
       sum(p.amount_usd)                                  AS collected_usd
FROM payments AS p
JOIN courses AS c ON c.course_id = p.course_id
GROUP BY ROLLUP (c.technology, c.title)
ORDER BY GROUPING(c.technology), c.technology, GROUPING(c.title), c.title;
Output
    technology    |      course       | collected_usd
------------------+-------------------+---------------
 Java             | Java Basics       |        450.00
 Java             | Java Collections  |        550.00
 Java             | Java OOP          |        500.00
 Java             | Subtotal          |       1500.00
 JavaScript       | JavaScript Basics |        450.00
 JavaScript       | Subtotal          |        450.00
 SQL              | SQL Basics        |        200.00
 SQL              | Subtotal          |        200.00
 All technologies | Subtotal          |       2150.00
(9 rows)

Explanation: GROUPING(col) is 1 on the rows ROLLUP added, so the labels say Subtotal and All technologies instead of NULL. Java brings in $1,500.00 across three courses, and the grand total is $2,150.00. The ordering puts each technology's courses first, then its subtotal, with the grand total last.

Part 5: Who Still Owes

For each active enrollment, compare the course fee with what has been paid for it (LEFT JOIN, HAVING):

SQL▶ Try it
SELECT s.first_name, c.title, c.fee_usd,
       coalesce(sum(p.amount_usd), 0.00)             AS paid_usd,
       c.fee_usd - coalesce(sum(p.amount_usd), 0.00) AS owed_usd
FROM enrollments AS e
JOIN students AS s ON s.student_id = e.student_id
JOIN courses  AS c ON c.course_id  = e.course_id
LEFT JOIN payments AS p
  ON p.student_id = e.student_id AND p.course_id = e.course_id
WHERE e.status = 'active'
GROUP BY s.first_name, c.title, c.fee_usd
HAVING c.fee_usd - coalesce(sum(p.amount_usd), 0.00) > 0
ORDER BY owed_usd DESC, s.first_name, c.title;
Output
 first_name |    title    | fee_usd | paid_usd | owed_usd
------------+-------------+---------+----------+----------
 Advitha    | Java Basics |  450.00 |     0.00 |   450.00
 Advitha    | SQL Basics  |  400.00 |     0.00 |   400.00
 Srihitha   | SQL Basics  |  400.00 |   200.00 |   200.00
(3 rows)

Explanation: The LEFT JOIN to payments matches on both student and course, because a payment belongs to one enrollment. Advitha has paid nothing for her two courses, so she owes their full fees; Srihitha has paid $200.00 of SQL Basics' $400.00. HAVING keeps only enrollments with something still owed, and it filters on the aggregate, which WHERE can't do.

Ranked courses and the money still owed

The Report Review

Before Srihitha uses the report, review it the way a teammate would (SQL Style Guide):

CheckResult
Every part totals to the same grand totalMonthly totals and the ROLLUP grand total are both $2,150.00
No missing months or coursesgenerate_series and LEFT JOIN keep empty months and Git Basics
NULL handled on purposecoalesce for empty sums; NULL kept for "no previous month"
No division by zeroNULLIF(previous, 0)
Money to the centNUMERIC sums; no float anywhere
Stable orderEvery ORDER BY has a tie-breaker
Clear namescollected_usd, owed_usd, change_pct

The cross-check query proves the parts agree. If anyone changes one query and breaks a total, this returns false:

SQL▶ Try it
SELECT (SELECT sum(amount_usd) FROM payments)                 AS from_payments,
       (SELECT sum(t) FROM (SELECT sum(p.amount_usd) AS t
                            FROM payments p JOIN courses c USING (course_id)
                            GROUP BY c.technology) x)         AS from_technologies,
       (SELECT sum(amount_usd) FROM payments
        WHERE paid_on >= '2025-08-01' AND paid_on < '2026-02-01') AS from_months,
       (SELECT sum(amount_usd) FROM payments) =
       (SELECT sum(amount_usd) FROM payments
        WHERE paid_on >= '2025-08-01' AND paid_on < '2026-02-01') AS months_cover_everything;
Output
 from_payments | from_technologies | from_months | months_cover_everything
---------------+-------------------+-------------+-------------------------
       2150.00 |           2150.00 |     2150.00 | t
(1 row)

Explanation: All three ways of adding up the fees give $2,150.00, and the months in the report cover every payment. A check like this belongs next to the report: when a new payment arrives in February 2026, months_cover_everything turns false, a reminder to extend the month list.

Every part adds up to the same 2,150.00

Common Mistakes

Grouping payments alone for a monthly report. Empty months disappear. Start from a calendar and LEFT JOIN.

Dividing by last month's total without NULLIF. A zero month raises a division-by-zero error.

Summing a sum after a join that multiplies rows. Joining payments to enrollments and courses can repeat payment rows if the join keys are wrong; check totals against sum(amount_usd) FROM payments.

Formatting numbers in SQL for display. to_char(amount, '$9,999.00') turns numbers into text that can't be added up later. Format in the spreadsheet or app.

No cross-check. Parts of a report drift apart silently. Keep a query that proves they agree.

Interview Corner

How do you include months with no data in a monthly report?

Generate the list of months (generate_series in PostgreSQL, or a calendar table) and LEFT JOIN the data to it, using coalesce to show zero for empty months.

How do you calculate month-over-month change?

With lag(total) OVER (ORDER BY month) to get the previous month's value, then total - lag(...), and for a percentage divide by NULLIF(lag(...), 0) to avoid dividing by zero.

How do you add subtotals and a grand total to a grouped query?

GROUP BY ROLLUP (a, b), using GROUPING(col) to label the subtotal rows.

Practice

Challenge: Add a running total to the monthly report: for each month, the amount collected that month and the total collected so far, from August 2025.

Show solution
SQL▶ Try it
WITH months AS (
  SELECT generate_series(DATE '2025-08-01', DATE '2026-01-01', INTERVAL '1 month')::date AS month_start
),
monthly AS (
  SELECT m.month_start, coalesce(sum(p.amount_usd), 0.00) AS collected_usd
  FROM months AS m
  LEFT JOIN payments AS p
    ON p.paid_on >= m.month_start AND p.paid_on < m.month_start + INTERVAL '1 month'
  GROUP BY m.month_start
)
SELECT to_char(month_start, 'YYYY-MM') AS month,
       collected_usd,
       sum(collected_usd) OVER (ORDER BY month_start) AS collected_so_far_usd
FROM monthly
ORDER BY month_start;
Output
  month  | collected_usd | collected_so_far_usd
---------+---------------+----------------------
 2025-08 |        450.00 |               450.00
 2025-09 |          0.00 |               450.00
 2025-10 |        250.00 |               700.00
 2025-11 |        225.00 |               925.00
 2025-12 |       1025.00 |              1950.00
 2026-01 |        200.00 |              2150.00
(6 rows)

sum(...) OVER (ORDER BY month_start) adds each month to the ones before it (Running Totals, LAG and LEAD). The last running total, $2,150.00, matches the grand total from Part 4, one more cross-check that passes.

Quick check: Sales report

3 questions
1Why does the monthly report start from generate_series?
2What does NULLIF(previous, 0) prevent?
3In a ROLLUP result, how do you tell a subtotal row from a real NULL?

Key Takeaways

Was this tutorial helpful?

Lesson 113 of 115