CODE WORKSPACE

Detect upsert key violations

Return status and buyers (the count of distinct buyer_id values) for each status. Order by buyers descending, then status ascending.

GROUP BY status with COUNT(DISTINCT buyer_id) AS buyers, then ORDER BY buyers DESC, status ASC.

Sample input

ordersThe 6 paid orders belong to buyers 1, 3, 2, 3, 6, 2 — only 4 distinct buyers.
order_idbuyer_idstatus
10011paid
10023paid
10052paid
10073paid
10106paid
10112paid

Expected output

Expected outputDistinct buyers per status, most first. paid has 6 orders but only 4 distinct buyers.
statusbuyers
paid4
shipped3
pending2
refunded1

Constraints

GROUP BY status. Use COUNT(DISTINCT buyer_id) AS buyers so repeat buyers are counted once. Order by buyers DESC, status ASC.

Expected skills

Counting unique entities with COUNT(DISTINCT ...) inside groups.

SQL
Loading...

AI evaluation

Run the SQL query to inspect preview rows.