CODE WORKSPACE

Clean order status CTE

Using a cleanup CTE, map status into clean_status ('complete_or_paid' for paid or shipped, 'open' for pending, otherwise the status itself), then return clean_status and the order count per bucket. Order by orders descending, then clean_status ascending.

First CTE builds clean_status with CASE; the outer query groups and counts it.

Sample input

ordersCASE maps paid/shipped → 'complete_or_paid', pending → 'open', else the status itself.
order_idstatus
1001paid
1004shipped
1003pending
1006refunded
1010paid

Expected output

Expected outputCounts per cleaned bucket: paid(6)+shipped(3)=complete_or_paid 9, pending(2)=open, refunded(1). Most first.
clean_statusorders
complete_or_paid9
open2
refunded1

Constraints

Do the CASE mapping in one cleanup CTE, then GROUP BY clean_status with COUNT(*) AS orders. Order by orders DESC, clean_status ASC.

Expected skills

Centralising a CASE in a cleanup CTE, then aggregating the cleaned shape.

SQL
Loading...

AI evaluation

Run the SQL query to inspect preview rows.