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_no starting with 202401).
  • One row per grade of the ordering customer, and one row at the bottom for all grades together. The total row's grade is the string TOTAL.
  • 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

ColumnMeaning
gradeVIP, GOLD, NORMAL, TOTAL
done_cntDONE count
paid_cntPAID count
canceled_cntCANCELED count
total_cntTotal count
cancel_pctCancel 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 it grade is NULL and GROUPING(c.grade) is 1 (ROLLUP).
  • The required order is not alphabetical, so give ORDER BY an order number with CASE.
  • Dividing integers drops the fraction in SQL Server and PostgreSQL. Mix in a decimal such as 100.0.