16. The checkout funnel Solved
AdvancedHardconditional aggregationbool_orfunnels
Per session_id, a session viewed if it has a page_view, carted if it viewed and has an add_to_cart, and checked out if it carted and has a checkout. Return three rows, step ('page_view', 'add_to_cart', 'checkout'), sessions, and pct_of_previous (1 decimal, NULL for page_view), in funnel order.
Your answer returns 3 rows with the columns step, sessions, pct_of_previous. 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
id | INTEGER primary key |
name | VARCHAR |
country | VARCHAR |
currency | VARCHAR EUR, GBP, USD or JPY |
signed_up | DATE |
tags | VARCHAR[] a list: vip, newsletter, b2b, returns-often |
products10 rows
id | INTEGER primary key |
name | VARCHAR |
category | VARCHAR |
price | DECIMAL(10,2) EUR |
specs | STRUCT weight_g INTEGER, color VARCHAR, sizes VARCHAR[] |
orders300 rows
id | INTEGER primary key |
customer_id | INTEGER → customers.id |
placed_at | TIMESTAMP 2024 |
status | ENUM placed, paid, shipped, delivered, returned |
currency | VARCHAR the customer's currency |
order_items576 rows
order_id | INTEGER → orders.id |
product_id | INTEGER → products.id |
quantity | INTEGER |
unit_price | DECIMAL(10,2) EUR |
web_events20,000 rows
event_id | BIGINT |
ts | TIMESTAMP |
session_id | VARCHAR |
customer_id | INTEGER NULL for anonymous visitors |
event_type | VARCHAR page_view, search, add_to_cart, checkout |
page | STRUCT path, referrer |
device | STRUCT browser, mobile BOOLEAN, screen STRUCT(w, h) |
product_ids | INTEGER[] |
load_ms | INTEGER |
fx_rates720 rows
currency | VARCHAR USD, GBP, JPY |
valid_from | TIMESTAMP |
per_eur | DOUBLE units of currency per 1 EUR |
Hints
bool_or(event_type = ...), then count.Common traps
- Counting events instead of sessions.
Solution
WITH s AS (
SELECT session_id,
bool_or(event_type = 'page_view') AS viewed,
bool_or(event_type = 'add_to_cart') AS carted,
bool_or(event_type = 'checkout') AS checked_out
FROM web_events GROUP BY session_id
), steps AS (
SELECT 1 AS ord, 'page_view' AS step, count(*) FILTER (WHERE viewed) AS sessions FROM s
UNION ALL SELECT 2, 'add_to_cart', count(*) FILTER (WHERE viewed AND carted) FROM s
UNION ALL SELECT 3, 'checkout', count(*) FILTER (WHERE viewed AND carted AND checked_out) FROM s
)
SELECT step, sessions,
round(100.0 * sessions / lag(sessions) OVER (ORDER BY ord), 1) AS pct_of_previous
FROM steps
ORDER BY ord
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.