Practice 1: Monthly VIP Sales
The sales team asks: "How did VIP sales move month by month in 2024? We also want to see how much each month rose or fell against the month before."
Requirements
- Count only orders of customers whose grade (
customers.grade) isVIP. - Count only orders whose status (
orders.status) isDONE. - Count only 2024 orders: those whose order number
ord_nostarts with2024. - One row per month: the order count, the total amount (
amt), and the difference from the previous month's total. The first month (January) has aNULLdifference.
Result format
| Column | Meaning |
|---|---|
ym | Year-month string, the first 6 characters of ord_no (e.g. 202401) |
ord_cnt | Number of orders |
total_amt | Total amount |
diff_amt | total_amt − the previous month's total_amt |
Sort by ym ascending. The result has 12 rows.
My solution
The SQL below only lists the VIP orders of January 2024. Change it to meet the requirements.
My solution
SELECT o.ord_no, o.status, o.amt, c.grade
FROM orders o
JOIN customers c ON c.cust_id = o.cust_id
WHERE c.grade = 'VIP'
AND o.ord_no LIKE '202401%'
ORDER BY o.ord_no
Hints
- The first 6 characters are
SUBSTR(ord_no, 1, 6)in Oracle and PostgreSQL andSUBSTRING(ord_no, 1, 6)in SQL Server (Expressions and functions). - Build the monthly totals first in an inline view or WITH, then fetch the previous month's value outside with
LAG(total_amt) OVER (ORDER BY ym)(Window functions). Window functions are computed over the rows left after aggregation.