N058-M3 Tier 5 · Expert · medium ecommerce · Brightlane

Return every customer who has placed at least one order, with their `id`, name, total revenue from delivered orders, total revenue from cancelled orders, and total order count

Part of Multi-CTE Query Architecture in SQL

The problem

Scenario: Brightlane's revenue analytics team is reviewing each customer's order outcomes to understand delivery success and cancellation exposure.

Task: Write a query to return every customer who has placed at least one order, with their id, name, total revenue from delivered orders, total revenue from cancelled orders, and total order count.

Assumptions:

  • A delivered order has status equal to 'delivered'. A cancelled order has status equal to 'cancelled'. Other statuses do not contribute to either revenue total but do contribute to the order count.
  • Some customers have no delivered orders, some have no cancelled orders, and some have neither; the corresponding revenue value for those customers is reported as a missing value.

Output:

  • One row per customer who has placed at least one order.
  • Columns in this order: customer_id, name, delivered_revenue, cancelled_revenue, order_count.
  • Sorted by delivered_revenue descending with missing values last; ties broken by customer_id ascending.
Schema · ecommerce 5 tables
categories
id integer
name text
parent_id? integer
products
id integer
name text
category_id integer
price numeric
stock_qty integer
attributes? jsonb
order_items
id integer
order_id integer
product_id integer
quantity integer
unit_price numeric
customers
id integer
name text
email text
city? text
country text
created_at timestamptz
is_active boolean
orders
id integer
customer_id integer
ordered_at timestamptz
status text
total_amount numeric

Run previews · Check grades

Write a query, then run it to see results here.

Worked solution Try it yourself first
Solution query
WITH
  order_results AS (
    SELECT
      o.customer_id,
      SUM(
        CASE
          WHEN o.status = 'delivered' THEN o.total_amount
        END
      ) AS delivered_revenue,
      SUM(
        CASE
          WHEN o.status = 'cancelled' THEN o.total_amount
        END
      ) AS cancelled_revenue,
      COUNT(*) AS order_count
    FROM
      orders o
    GROUP BY
      o.customer_id
  ),
  customer_view AS (
    SELECT
      c.id AS customer_id,
      c.name,
      r.delivered_revenue,
      r.cancelled_revenue,
      r.order_count
    FROM
      customers c
      JOIN order_results r ON r.customer_id = c.id
  )
SELECT
  customer_id,
  name,
  delivered_revenue,
  cancelled_revenue,
  order_count
FROM
  customer_view
ORDER BY
  delivered_revenue DESC NULLS LAST,
  customer_id

The shape

Two CTEs, with the conditional aggregation done once in the first and the customer name attached afterward in the second. The per-status sums are computed using CASE inside the aggregate, so the entire status split happens in a single pass over orders and the customer table joins in only after the totals exist.

Clause by clause

WITH order_results AS (
    SELECT
        o.customer_id,
        SUM(CASE WHEN o.status = 'delivered' THEN o.total_amount END) AS delivered_revenue,
        SUM(CASE WHEN o.status = 'cancelled' THEN o.total_amount END) AS cancelled_revenue,
        COUNT(*) AS order_count
    FROM orders o
    GROUP BY o.customer_id
)

GROUP BY o.customer_id produces one row per customer. Each SUM(CASE WHEN ...) adds the total_amount only on rows matching its status and contributes nothing on the others. The CASE with no ELSE returns NULL on non-matching rows, and SUM skips nulls, which is why a customer with no delivered orders ends up with NULL for delivered_revenue instead of 0. COUNT(*) runs over every order regardless of status, so the total order count includes the other statuses too.

customer_view AS (
    SELECT c.id AS customer_id, c.name, r.delivered_revenue, r.cancelled_revenue, r.order_count
    FROM customers c
    JOIN order_results r ON r.customer_id = c.id
)

The customer record joins in only here, attaching the readable name to each per-customer totals row. The join is an inner join, so customers with no orders never appear, which matches the "at least one order" requirement.

  • SELECT customer_id, name, delivered_revenue, cancelled_revenue, order_count FROM customer_view ORDER BY delivered_revenue DESC NULLS LAST, customer_id sorts the biggest delivered earners first, sends the no-delivery customers to the bottom via NULLS LAST, and breaks ties by ID.

Why CASE WHEN without ELSE 0 and not ELSE 0

The prompt asks for missing values when there is no delivered revenue, not 0. SUM(CASE WHEN ... THEN ... END) returns NULL when no row matches because every CASE evaluation produced NULL and SUM of all-nulls is NULL. Adding ELSE 0 would make those sums 0 instead, which reads as "delivered $0" rather than "no delivered orders." The two are different facts about the customer, and the prompt wants the distinction preserved.

You practiced separating per-status revenue into one CTE and attaching customer identity in another, so the conditional totals are computed once and labelled afterward.

How you actually get good at SQL

Reading explains SQL. Writing it, over and over with instant feedback, is what makes you fluent.

That's the whole SQLMaxx loop: 600+ real problems, instant AI feedback, mastery you can actually see, and spaced review that won't let you forget.

A stack of SQL practice problem cards, the top card showing an employees table.
615 problems · 66 concepts

Real problems. Not toy examples.

615 hand-built problems spanning all 66 concepts, from basic SELECTs to window functions, built on real schemas and real business questions, the kind you'll actually get asked on the job. Enough reps to make SQL automatic.

A retro computer showing a SQL query marked correct with a green checkmark.
Instant AI feedback

Write a query. Know if it's right in one second.

No copying an answer and hoping it clicked. The AI grader checks your real query against real data, catches exactly what's wrong, and explains the fix in plain English, like a senior analyst reading over your shoulder on every problem.

A circular mastery progress dial filling from blue to green, the SQLMaxx diamond at its center.
Mastery tracking

Stop guessing whether you actually know it.

SQLMaxx tracks every concept and shows you what you've mastered and what's still shaky. Your skills fill in one concept at a time, so 'I think I get joins' becomes something you can prove.

A SQL query editor circled by a blue return arrow with a clock, scheduled to come back for review.
Spaced review

Learn it once. Keep it for good.

Most of what you learn this week fades by next week. So when a concept comes due for review, SQLMaxx hands you a fresh problem to solve from a blank editor, not a flashcard to re-read. A research-backed spaced-repetition algorithm (FSRS) times each return for right before you'd forget, so your SQL is still there months later, when the interview or the job actually needs it.

Practice, feedback, mastery, review. That's the loop that turns reading into real skill.

Start free

No account, no credit card. Start solving in under a minute.