Practice 4: VIPs Who Stopped Buying
Customer care wants to contact customers at risk of leaving: "Give us the VIPs with not a single completed order in 2025. Also how many times they have bought, and what their last order was."
Requirements
- Only customers of grade
VIPthat have no order withstatus = 'DONE'in 2025 (ord_nostarting with2025). Customers with onlyPAIDorCANCELEDorders in 2025 are included. - For each customer, add the number of
DONEorders over the whole period and the largestord_noamong them (the last completed order). - A VIP with no
DONEorder at all, if any, must show a count of 0 and aNULLlast order number.
Result format
| Column | Meaning |
|---|---|
cust_id | Customer number |
cust_nm | Customer name |
region | Region |
done_cnt | Number of DONE orders over the whole period |
last_ord_no | Last DONE order number |
Order does not matter.
My solution
My solution
SELECT c.cust_id, c.cust_nm, c.region
FROM customers c
WHERE c.grade = 'VIP'
ORDER BY c.cust_id
Hints
- "Customers with no …" is a correlated
NOT EXISTSsubquery (Subqueries, Subquery comparisons). Be careful withNOT IN: aNULLin the subquery empties the result. - To keep customers without orders, use
LEFT JOIN, and put theDONEcondition inON, not inWHERE. InWHEREit turns the outer join into an inner join (Outer joins). COUNT(*)counts an unmatched row as 1. Count a column of the order side to get 0.