Practice 5: Grade × Order Status Table
A table for the operations report: "Spread January 2024 orders by grade, with the count of each status side by side. We also need the cancel rate and a total line at the bottom."
Requirements
- Count only January 2024 orders (
ord_nostarting with202401). - One row per grade of the ordering customer, and one row at the bottom for all grades together. The total row's
gradeis the stringTOTAL. - Spread the count of each status (
DONE,PAID,CANCELED) into its own column and add the total count. - Cancel rate = canceled count × 100 / total count, rounded to 2 decimal places.
Result format
| Column | Meaning |
|---|---|
grade | VIP, GOLD, NORMAL, TOTAL |
done_cnt | DONE count |
paid_cnt | PAID count |
canceled_cnt | CANCELED count |
total_cnt | Total count |
cancel_pct | Cancel rate (%) |
The row order is VIP, GOLD, NORMAL, TOTAL.
My solution
My solution
SELECT c.grade, o.status, COUNT(*) AS cnt
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
WHERE o.ord_no LIKE '202401%'
GROUP BY c.grade, o.status
ORDER BY c.grade, o.status
Hints
- Turning rows into columns is
SUM(CASE WHEN … THEN 1 ELSE 0 END)(Pivot). GROUP BY ROLLUP (c.grade)makes the total row. In itgradeisNULLandGROUPING(c.grade)is 1 (ROLLUP).- The required order is not alphabetical, so give
ORDER BYan order number withCASE. - Dividing integers drops the fraction in SQL Server and PostgreSQL. Mix in a decimal such as
100.0.