15. Rebuild sessions from raw events Solved
AdvancedExpertsessionizationLAGrunning SUMNULLs
Ignore session_id and rebuild sessions yourself: for identified visitors (customer_id not NULL), a new session starts with a customer's first event and whenever more than 30 minutes passed since their previous event. Return the 5 customers with the most sessions: customer_id, sessions, events. Sort by sessions descending, then customer_id. (Order events by ts, then event_id.)
Your answer returns 5 rows with the columns customer_id, sessions, events. 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
Common traps
- Anonymous events (NULL
customer_id) would all fall into one giant "customer".
Solution
WITH flagged AS (
SELECT customer_id,
CASE WHEN lag(ts) OVER w IS NULL OR ts - lag(ts) OVER w > INTERVAL 30 MINUTE THEN 1 ELSE 0 END AS starts
FROM web_events
WHERE customer_id IS NOT NULL
WINDOW w AS (PARTITION BY customer_id ORDER BY ts, event_id)
)
SELECT customer_id, sum(starts) AS sessions, count(*) AS events
FROM flagged
GROUP BY customer_id
ORDER BY sessions DESC, customer_id
LIMIT 5
Free for personal practice. Please don't republish the questions or solutions. See the Playground License Terms.