Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 3

Turning Rows into Business Metrics

Build the store dashboard: totals with count, sum, min, max and avg, monthly revenue with GROUP BY and HAVING, status pivots with CASE, and shares with count DISTINCT and round.

Contentsand lesson path

What you will learn

  • Summarize data with GROUP BY, HAVING, aggregate functions and CASE-based conditional aggregation.

01. Goal and setup

Raw rows answer "which orders exist"; businesses ask "how much, how many, per what". This lab turns the store data from the joins lesson into five numbers a manager actually wants:

  1. How many orders, and how many have shipped?
  2. Order counts by status.
  3. Revenue per month, ignoring cancelled orders — and which months cleared 300?
  4. The status mix per month, side by side.
  5. Average order value, and each category's share of revenue.

You need: the store database as loaded in the previous lesson. Connect with psql as before. Every output below was run against exactly that data, so you can compare line by line.

02. Step 1: aggregate the whole table

An aggregate function collapses many rows into one value: count, sum, min, max, avg. Applied to the whole table, you get headline numbers. One subtlety first: count(*) counts rows, while count(column) skips rows where that column is NULL — on our data, shipped_at is set only once an order ships, so the two counts differ:

SQL · store=#
SELECT count(*)            AS orders,
       count(shipped_at)   AS shipped,
       min(created_at)     AS first_order,
       max(created_at)     AS last_order
FROM orders;
Expected output
 orders | shipped | first_order | last_order 
--------+---------+-------------+------------
     10 |       5 | 2026-06-14  | 2026-09-22
(1 row)

Ten orders, five shipped, and the trading window June to September 2026. The same skipping rule applies to avg and sum: they ignore NULLs rather than treating them as zero, which is right — an absent rating is not a zero-star rating. If a NULL genuinely means zero in your domain, say so with COALESCE(x, 0).

03. Step 2: one group per value with GROUP BY

Aggregating everything is blunt; GROUP BY splits the table into groups — one per distinct value of the grouping column — and aggregates each group separately, returning one row per group:

SQL · ask 2
SELECT status, count(*) AS orders
FROM orders
GROUP BY status
ORDER BY orders DESC;
Expected output
  status   | orders 
-----------+--------
 shipped   |      5
 paid      |      3
 cancelled |      2
(3 rows)

One rule keeps GROUP BY honest: every column in SELECT must be either in the GROUP BY list or inside an aggregate. Asking for status, name grouped by status makes no sense — which of the group's names would show? PostgreSQL rejects it rather than guessing. (It relaxes the rule in one case: if you group by a table's primary key, you may select that table's other columns, such as GROUP BY c.id with c.name in SELECT, because each group has exactly one value for them.) Grouping works on several columns too (GROUP BY country, status gives country-status cells), and NULL forms its own group: grouping customers by country puts Ben and Dmitri together in the NULL group.

04. Step 3: revenue per month — WHERE before, HAVING after

Monthly revenue needs three ideas at once: an arithmetic expression inside sum (quantity * unit_price per item row), a date function to bucket dates into months, and a row filter. date_trunc('month', d) rounds any date down to the first of its month; casting with ::date drops the time part for tidy output. Cancelled orders are removed before grouping, in WHERE, because that is a fact about a row:

SQL · ask 3
SELECT date_trunc('month', o.created_at)::date AS month,
       sum(i.quantity * i.unit_price)          AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1
ORDER BY 1;
Expected output
   month    | revenue 
------------+---------
 2026-06-01 |   48.80
 2026-07-01 |  375.50
 2026-08-01 |  134.00
 2026-09-01 |  370.40
(4 rows)

GROUP BY 1 means "group by the first selected column", a handy shorthand for long expressions. Now keep only the strong months. You cannot write WHERE sum(...) >= 300: WHERE runs before groups exist, so aggregates are not available there. HAVING runs after grouping and filters whole groups:

SQL · ask 3, strong months only
SELECT date_trunc('month', o.created_at)::date AS month,
       sum(i.quantity * i.unit_price)          AS revenue
FROM orders o
JOIN order_items i ON i.order_id = o.id
WHERE o.status <> 'cancelled'
GROUP BY 1
HAVING sum(i.quantity * i.unit_price) >= 300
ORDER BY 1;
Expected output
   month    | revenue 
------------+---------
 2026-07-01 |  375.50
 2026-09-01 |  370.40
(2 rows)

The rule is now mechanical: facts about single rows go in WHERE; facts about groups go in HAVING. "Status is not cancelled" describes a row; "revenue at least 300" describes a month. HAVING also works without GROUP BY, filtering the single all-rows group.

05. Step 4: several metrics side by side with CASE

Ask 4 wants counts of shipped, paid and cancelled orders per month, in one result. The trick is conditional aggregation: a CASE expression returns 1 for rows that match a condition and NULL for the rest, and count skips the NULLs. CASE is general-purpose — it is an expression usable anywhere a value is expected — and this pivot is its most common analytical job:

SQL · ask 4
SELECT date_trunc('month', o.created_at)::date AS month,
       count(CASE WHEN o.status = 'shipped'   THEN 1 END) AS shipped,
       count(CASE WHEN o.status = 'paid'      THEN 1 END) AS paid,
       count(CASE WHEN o.status = 'cancelled' THEN 1 END) AS cancelled
FROM orders o
GROUP BY 1
ORDER BY 1;
Expected output
   month    | shipped | paid | cancelled 
------------+---------+------+-----------
 2026-06-01 |       1 |    0 |         0
 2026-07-01 |       1 |    1 |         0
 2026-08-01 |       1 |    1 |         1
 2026-09-01 |       2 |    1 |         1
(4 rows)

The missing ELSE is the point: with no ELSE branch, CASE yields NULL for non-matching rows, and only then does count skip them. Writing ELSE 0 breaks the count — 0 is a value, and count counts values. If you prefer summing, sum(CASE WHEN ... THEN 1 ELSE 0 END) works too, because adding zeros changes nothing. The shorter count(*) FILTER (WHERE ...) is also standard SQL (since SQL:2003) and PostgreSQL supports it, but not every engine does (MySQL and SQL Server do not); the CASE form works everywhere.

06. Step 5: average order value — aggregate first, join after

The average order value is not the average of item rows — each order must be totalled first, and only then averaged. That is the derived table pattern from the joins lesson: a subquery in FROM produces one row per order, and the outer query aggregates the aggregates:

SQL · ask 5a
SELECT round(avg(t.order_total), 2) AS avg_order_value
FROM (SELECT o.id,
             sum(i.quantity * i.unit_price) AS order_total
      FROM orders o
      JOIN order_items i ON i.order_id = o.id
      WHERE o.status <> 'cancelled'
      GROUP BY o.id) t;
Expected output
 avg_order_value 
-----------------
          116.09
(1 row)

Eight non-cancelled orders, 928.70 of revenue, 116.09 on average — and no join fan-out distorted it, because the sum happened inside the per-order subquery. The same discipline gives honest customer counts: how many distinct customers ordered each month? count(DISTINCT customer_id) collapses repeats, and the guest checkout simply contributes no customer:

SQL · store=#
SELECT date_trunc('month', created_at)::date AS month,
       count(DISTINCT customer_id)            AS customers
FROM orders
GROUP BY 1
ORDER BY 1;
Expected output
   month    | customers 
------------+-----------
 2026-06-01 |         1
 2026-07-01 |         2
 2026-08-01 |         3
 2026-09-01 |         3
(4 rows)

07. Step 6: each category's share of revenue

Shares need a numerator per group and one total. The category revenue is a plain GROUP BY; the total is the same aggregation without grouping, attached with a cross join against a one-row subquery — a legitimate cross join, since one side has exactly one row. round(x, 1) trims the result to one decimal:

SQL · ask 5b
SELECT c.category,
       c.revenue,
       round(100 * c.revenue / t.total, 1) AS pct
FROM (SELECT p.category,
             sum(i.quantity * i.unit_price) AS revenue
      FROM orders o
      JOIN order_items i ON i.order_id = o.id
      JOIN products p ON p.id = i.product_id
      WHERE o.status <> 'cancelled'
      GROUP BY p.category) c
CROSS JOIN (SELECT sum(i.quantity * i.unit_price) AS total
            FROM orders o
            JOIN order_items i ON i.order_id = o.id
            WHERE o.status <> 'cancelled') t
ORDER BY c.revenue DESC;
Expected output
  category   | revenue | pct  
-------------+---------+------
 displays    |  498.00 | 53.6
 peripherals |  268.00 | 28.9
 accessories |  162.70 | 17.5
(3 rows)

Displays are 53.6% of revenue from just two sold units — the kind of sentence a dashboard exists to surface, built from GROUP BY, a join, a cross join and round. When you need the total and the detail without a cross join, window functions (OVER ()) do it in one pass; you will meet them in later skills.

08. Troubleshooting

09. Check your understanding

Practice check · 3 questions

Aggregation rules

Three situations from reporting work.

Q1. orders holds 10 rows. customer_id values are 1, 2, 1, 3, 2, 5, 3, 6, NULL, 5. What do count(customer_id) and count(DISTINCT customer_id) return?
Q2. A report shows, per country, customers who joined in 2026, and keeps only countries with more than one such customer. Where does each condition belong?
Q3. SELECT country, name FROM customers GROUP BY country; — what does PostgreSQL do?
Practice only: not graded, not saved, not evidence.

10. Apply it

Grow the practice project's query set:

  1. Revenue per customer for non-cancelled orders, with a HAVING that keeps customers above 100 — Amara's cancelled mouse pad must not distort the number, so filter before grouping.
  2. A monthly pivot of items sold versus distinct products sold per month (sum(quantity) next to count(DISTINCT product_id)).
  3. Rewrite the monthly status pivot from Step 4 with count(*) FILTER (WHERE ...) in place of one of the CASE expressions to see PostgreSQL's native aggregate filter syntax.

These reports are candidates to save as views, which the next lesson does. Validating each row before it enters a report is the job of schema rules — see schema validation with Pydantic for the same idea at the API boundary.

11. Review prompt

Without looking back:

  1. What is the difference between count(*), count(column) and count(DISTINCT column), and how do sum and avg treat NULLs?
  2. State the WHERE-versus-HAVING rule and why aggregates are illegal in WHERE.
  3. Why does count(CASE WHEN cond THEN 1 END) count matching rows, and what breaks if you add ELSE 0?
  4. Why must order totals be computed in a subquery before averaging, rather than averaged straight off joined item rows?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check