Overview
Build March's order report in one query: count the orders, count the shipped ones and total their revenue with conditional aggregation.
- SUM(CASE WHEN ... THEN 1 ELSE 0 END)
- Date range plus aggregates
- One row, several numbers
Short Course
To count several things in one pass, put CASE inside an aggregate:
SUM(CASE WHEN ... THEN 1 ELSE 0 END) counts the matching rows. Trap:
COUNT(CASE ...) counts the 0s too, because COUNT counts every value that
isn't NULL.
SELECT COUNT(*) AS orders,
SUM(CASE WHEN coupon IS NOT NULL THEN 1 ELSE 0 END) AS with_coupon,
SUM(CASE WHEN coupon IS NULL THEN total ELSE 0 END) AS full_price_revenue
FROM orders;
Task
For orders placed in March 2024, return one row: the number of orders, how
many have shipped (shipped_at is set), and the revenue of the shipped ones
rounded to 2 decimals. In the database below, March has 3 orders and 2 of them
have shipped.
Database
Sample data from the first test. The other tests use different rows, so write a query, not a list of answers.
| idINTEGER | created_atTEXT | totalREAL | shipped_atTEXT |
|---|---|---|---|
| 1 | 2024-02-28 10:00 | 50.0 | 2024-03-01 |
| 2 | 2024-03-02 09:00 | 20.5 | 2024-03-03 |
| 3 | 2024-03-10 14:00 | 35.25 | NULL |
| 4 | 2024-03-31 21:00 | 44.25 | 2024-04-01 |
| 5 | 2024-04-01 08:00 | 12.0 | NULL |
Test Suites
Pending
Next
Output