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 VIP that have no order with status = 'DONE' in 2025 (ord_no starting with 2025). Customers with only PAID or CANCELED orders in 2025 are included.
  • For each customer, add the number of DONE orders over the whole period and the largest ord_no among them (the last completed order).
  • A VIP with no DONE order at all, if any, must show a count of 0 and a NULL last order number.

Result format

ColumnMeaning
cust_idCustomer number
cust_nmCustomer name
regionRegion
done_cntNumber of DONE orders over the whole period
last_ord_noLast 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 EXISTS subquery (Subqueries, Subquery comparisons). Be careful with NOT IN: a NULL in the subquery empties the result.
  • To keep customers without orders, use LEFT JOIN, and put the DONE condition in ON, not in WHERE. In WHERE it 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.