AI Hints
Home›PostgreSQL Tutorial›DISTINCT ON, generate_series, Report
PostgreSQL · Lesson 36 of 120

Practice: The Monthly Report

Put it together.

⏱ 2 min read▶ Video at 31:21🎓 Free
Watch this lesson in the PostgreSQL courseWatch on YouTube ↗Full PostgreSQL course

Let's build the owner's monthly report for the first quarter of twenty twenty five. Orders, revenue, the best selling genre, and growth from the month before.

  • Orders
  • Revenue
  • Top genre
  • Growth

The report

Lines totals each order line by month and genre. Monthly sums them. Distinct on picks the top genre per month. Lag gives growth. Run it. Three months, in one readable query.

query.sqlsql
WITH lines AS (
  SELECT date_trunc('month', o.order_date)::date AS month,
         b.genre, i.quantity * b.price AS amount, o.order_id
  FROM orders o JOIN order_items i USING (order_id) JOIN books b USING (book_id)
  WHERE o.order_date BETWEEN '2025-01-01' AND '2025-03-31'),
monthly AS (
  SELECT month, count(DISTINCT order_id) AS orders, sum(amount) AS revenue
  FROM lines GROUP BY month),
top AS (
  SELECT DISTINCT ON (month) month, genre FROM lines
  GROUP BY month, genre ORDER BY month, sum(amount) DESC)
SELECT m.month, m.orders, m.revenue, t.genre AS top_genre,
       round(100 * (m.revenue / lag(m.revenue) OVER (ORDER BY m.month) - 1), 1) AS growth
FROM monthly m JOIN top t USING (month) ORDER BY m.month;
Output
   month    | orders | revenue | top_genre  | growth
------------+--------+---------+------------+--------
 2025-01-01 |     69 | 2120.24 | Technology |
 2025-02-01 |     75 | 2465.13 | Technology |   16.3
 2025-03-01 |     61 | 1952.82 | Thriller   |  -20.8
(3 rows)

What we used

CTEs to name each step. Date trunc to group by month. Distinct on for the top genre. And lag for growth. Real reports are just these small pieces, put together.

keyvalue
CTEsnamed steps
date_truncmonths
DISTINCT ONtop genre
lag()growth

Summary

A real report is small steps, joined into one query. Next, Postgres arrays.

Key takeaways
  • CTEs
  • DISTINCT ON
  • lag
Next up: Arrays — lists in a column