Get Started Free

25. Pivot in one pass Solved

PerformanceMediumFILTER clausePIVOTsingle scan

Return one row per month of 2024: month ("YYYY-MM") and the number of orders in each status as columns placed, paid, shipped, delivered, returned (0 when none). Sort by month. Constraint: read orders once. No UNION ALL of per-status queries, no subquery per column.

Your answer returns 12 rows with the columns month, placed, paid, shipped, delivered, returned. Order matters.

The data

The store from the DuckDB playground, running in your browser with DuckDB. Prices are in EUR; the data covers 2024.

customers20 rows
idINTEGER
primary key
nameVARCHAR
countryVARCHAR
currencyVARCHAR
EUR, GBP, USD or JPY
signed_upDATE
tagsVARCHAR[]
a list: vip, newsletter, b2b, returns-often
products10 rows
idINTEGER
primary key
nameVARCHAR
categoryVARCHAR
priceDECIMAL(10,2)
EUR
specsSTRUCT
weight_g INTEGER, color VARCHAR, sizes VARCHAR[]
orders300 rows
idINTEGER
primary key
customer_idINTEGER
→ customers.id
placed_atTIMESTAMP
2024
statusENUM
placed, paid, shipped, delivered, returned
currencyVARCHAR
the customer's currency
order_items576 rows
order_idINTEGER
→ orders.id
product_idINTEGER
→ products.id
quantityINTEGER
unit_priceDECIMAL(10,2)
EUR
web_events20,000 rows
event_idBIGINT
tsTIMESTAMP
session_idVARCHAR
customer_idINTEGER
NULL for anonymous visitors
event_typeVARCHAR
page_view, search, add_to_cart, checkout
pageSTRUCT
path, referrer
deviceSTRUCT
browser, mobile BOOLEAN, screen STRUCT(w, h)
product_idsINTEGER[]
load_msINTEGER
fx_rates720 rows
currencyVARCHAR
USD, GBP, JPY
valid_fromTIMESTAMP
per_eurDOUBLE
units of currency per 1 EUR

Hints

Common traps
  • One query per status glued with UNION ALL / joins scans the table five times.

Solution

Run in the editor with Ctrl/⌘ + Enter. Check with Shift + Ctrl/⌘ + Enter.

"Check answer" runs your SQL on a fresh copy of the data, then on 2 hidden test datasets with more customers and orders, and compares each result with the expected one. The result of your last statement is your answer.

Starting…