Coding question · Date TruncVery HardAsked at Stripe

Count sessions per customer (30-day gap)

Gaps-and-islands: segment a time series by gaps.

Back to all coding questions

The Brief

Growth AnalyticsRetention team#coding-interview

Define a customer 'session' as a run of orders where no two consecutive orders are more than 30 days apart. The first order starts a session; each gap > 30 days from the previous order starts a new session. For each customer, return the number of sessions. Columns: `customer_id`, `session_count`. Order by customer_id. Table: `ci_orders`.

Tables & columns available

ci_ordersfact6 columns
ColumnTypeKey
order_idINTPK
customer_idINT
product_nameTEXT
categoryTEXT
order_dateDATE
revenueNUMERIC

Hints (4)

Each hint you reveal reduces the XP you can earn. Try the query first.

Hint 1

LAG(order_date) OVER (PARTITION BY customer_id ORDER BY order_date) to get the prior order date.

Hint 2

Flag a row as a new-session start: (order_date - prev_date) > 30 OR prev_date IS NULL.

Hint 3

Cumulative SUM of the new-session flag OVER (PARTITION BY customer_id ORDER BY order_date) assigns a session_id.

Hint 4

Then GROUP BY customer_id and COUNT(DISTINCT session_id). Each of these steps belongs in its own CTE.