Multi-Stage Funnel Analysis in SQL: Windows, Dedup & Rollups
SQL & DataModel answerLast updated
Write ANSI-SQL to build a windowed conversion funnel, attribute acquisition channels, flag bot-like campaigns, deduplicate near-duplicate events, and compute rolling unique viewers.
Context
You are working with an event stream from a video streaming platform. All user activity is captured in a flat events table alongside user profiles and a content catalog. Use today = 2025-09-01 for any relative date calculations.
Schema
users(user_id STRING, created_at TIMESTAMP, country STRING, platform STRING)
events(
event_ts TIMESTAMP,
user_id STRING,
event_type STRING, -- one of: impression, click, signup, start_subscription, watch_start, watch_end
show_id STRING NULL,
session_id STRING,
revenue_cents INT NULL,
campaign_id STRING NULL
)
shows(show_id STRING, title STRING)
Sample Data
users
| user_id | created_at | country | platform |
|---|---|---|---|
| u1 | 2025-08-10 12:00:00 | US | iOS |
| u2 | 2025-08-25 09:00:00 | US | Web |
| u3 | 2025-08-30 08:30:00 | CA | Android |
| u4 | 2025-08-31 21:00:00 | US | iOS |
events
| event_ts | user_id | event_type | show_id | session_id | revenue_cents | campaign_id |
|---|---|---|---|---|---|---|
| 2025-08-26 10:01:00 | u1 | impression | s1 | sA | NULL | c10 |
| 2025-08-26 10:02:00 | u1 | click | s1 | sA | NULL | c10 |
| 2025-08-26 10:05:00 | u1 | signup | NULL | sA | NULL | NULL |
| 2025-08-27 11:00:00 | u1 | start_subscription | NULL | sA | 7999 | NULL |
| 2025-08-30 09:00:00 | u2 | impression | s2 | sB | NULL | c10 |
| 2025-08-30 09:01:00 | u2 | click | s2 | sB | NULL | c10 |
| 2025-08-31 12:00:00 | u2 | signup | NULL | sB | NULL | NULL |
| 2025-09-01 08:00:00 | u3 | impression | s1 | sC | NULL | c99 |
| 2025-09-01 08:00:02 | u3 | impression | s1 | sC | NULL | c99 |
| 2025-09-01 08:03:00 | u3 | click | s1 | sC | NULL | c99 |
| 2025-09-01 08:20:00 | u3 | watch_start | s1 | sC | NULL | NULL |
| 2025-09-01 08:50:00 | u3 | watch_end | s1 | sC | NULL | NULL |
| 2025-08-31 20:00:00 | u4 | impression | s3 | sD | NULL | NULL |
| 2025-09-01 07:30:00 | u4 | click | s3 | sD | NULL | NULL |
| 2025-09-01 07:40:00 | u4 | signup | NULL | sD | NULL | NULL |
shows
| show_id | title |
|---|---|
| s1 | The Bear |
| s2 | Only Murders |
| s3 | The Kardashians |
Tasks
a) Daily conversion funnel
Build a day-by-day funnel for each calendar date in [2025-08-26, 2025-09-01]. Attribute every user to the day of their first impression. A user advances through each stage only if the qualifying event falls within these windows:
- Click within 1 day of their impression
- Signup within 3 days of that click
- Subscription start within 7 days of that signup
Output columns: day, impressions, clicks_w1d, signups_w3d, subs_w7d, plus the three stage-to-stage conversion rates.
b) Time-to-first-watch by acquisition channel
For users who signed up in August 2025, compute — grouped by signup_date and acquisition_channel — the median number of minutes from signup to their first watch_start. Define acquisition channel as paid if any impression or click in the 7 days before signup had a non-null campaign_id, otherwise organic. Note that signup rows themselves never carry a campaign_id.
c) Suspicious campaign detection
Over the 7-day window [2025-08-26, 2025-09-01], flag any campaign where CTR > 0.80, total impressions ≥ 100, and distinct users ≤ 5. Return campaign_id, impressions, clicks, ctr, distinct_users.
d) Near-duplicate event deduplication
Within each (user_id, event_type, show_id) group, successive events less than or equal to 5 seconds apart are considered duplicates of the earlier one. Keep only the first event in each such burst. Produce a deduplicated ev CTE that all other parts can reference.
e) Bonus — 28-day rolling unique viewers
For each day across August and September 2025, count the distinct users who had a watch_start for each show_id in the trailing 28 days (inclusive). On 2025-09-01, return the top 3 shows by that metric, breaking ties by the highest single-day unique viewer count on that date.
For each part, provide working Snowflake-compatible SQL, note any edge cases in your approach, and explain how your solution holds up on a table with billions of rows (partitioning strategy, clustering keys, approximate aggregations).
Hints
Hint 1
Start with part (d): a single deduplicated CTE that every other query reads from saves you from re-solving dedup logic five times. Use LAG() partitioned by (user_id, event_type, show_id) ordered by event_ts to compare each event against its predecessor — if the gap is ≤ 5 seconds, drop it. Be explicit about how NULLs in show_id are handled: NULLs are grouped together, which is correct for signups.
Hint 2
For the funnel in part (a), resist the urge to do calendar-day comparisons. The windows (1 day, 3 days, 7 days) are timestamp-based intervals anchored to each user's qualifying event, not midnight-to-midnight buckets. Each stage CTE should pick the MIN qualifying timestamp per user per impression-day, then the next stage joins against that timestamp. Use a date spine with a recursive CTE or VALUES…
Hint 3
For the acquisition channel in part (b), the signup event itself has a NULL campaign_id in the data — you cannot read the channel from the signup row. Instead, look backward from the signup timestamp at the user's impression and click events in the prior 7 days and pick the most recent non-null campaign_id (MAX_BY(campaign_id, event_ts) in Snowflake). If none exists, the user is organic. For the r…
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Approach Overview
All five parts share one core habit: deduplicate once up front, then layer every analytical CTE on top of that clean base. The sections below build in dependency order: (d) first, then (a), (b), (c), (e).
Part (d) — Deduplicated event base CTE
WITH ev AS (
SELECT
event_ts, user_id, event_type, show_id,
session_id, revenue_cents, campaign_id
FROM (
SELECT
e.*,
LAG(event_ts) OVER (
PARTITION BY user_id, event_type, show_id
ORDER BY event_ts
) AS prev_ts
FROM events e
) x
WHERE prev_ts IS NULL
OR DATEDIFF('second', prev_ts, event_ts) > 5
)
LAG compares each event to the immediately preceding one in its (user_id, event_type, show_id) group. If the gap is ≤ 5 seconds it is dropped. NULL show_id values are grouped together, which is intentional — signup events have no show and should still be deduplicated against each other. In the sample data, u3's second impression at 08:00:02 is removed.
Important caveat: this is a gap-based rule, not an anchor-based one. A burst at 0 s, 4 s, 8 s drops all three events even though the third is 8 s after the first. A strict "within 5 s of the last kept event" rule would need MATCH_RECOGNIZE or a recursive CTE. For most product analytics, the gap rule is the right intent.
Part (a) — Daily windowed funnel
, date_spine AS (
SELECT DATE '2025-08-26' AS d
UNION ALL
SELECT DATEADD(day, 1, d) FROM date_spine WHERE d < DATE '2025-09-01'
)
, imp AS (
SELECT user_id, CAST(event_ts AS DATE) AS d, event_ts AS imp_ts
FROM ev
WHERE event_type = 'impression'
AND event_ts >= '2025-08-26' AND event_ts < '2025-09-02'
)
, clk AS (
SELECT i.user_id, i.d, MIN(e.event_ts) AS clk_ts
FROM imp i
JOIN ev e
ON e.user_id = i.user_id
AND e.event_type = 'click'
AND e.event_ts BETWEEN i.imp_ts AND DATEADD(day, 1, i.imp_ts)
GROUP BY i.user_id, i.d
)
, sgn AS (
SELECT c.user_id, c.d, MIN(e.event_ts) AS sgn_ts
FROM clk c
JOIN ev e
ON e.user_id = c.user_id
AND e.event_type = 'signup'
AND e.event_ts BETWEEN c.clk_ts AND DATEADD(day, 3, c.clk_ts)
GROUP BY c.user_id, c.d
)
, sub AS (
SELECT s.user_id, s.d
FROM sgn s
JOIN ev e
ON e.user_id = s.user_id
AND e.event_type = 'start_subscription'
AND e.event_ts BETWEEN s.sgn_ts AND DATEADD(day, 7, s.sgn_ts)
GROUP BY s.user_id, s.d
)
SELECT
ds.d AS day,
COUNT(DISTINCT i.user_id) AS impressions,
COUNT(DISTINCT c.user_id) AS clicks_w1d,
COUNT(DISTINCT s.user_id) AS signups_w3d,
COUNT(DISTINCT b.user_id) AS subs_w7d,
DIV0(COUNT(DISTINCT c.user_id), COUNT(DISTINCT i.user_id)) AS imp_to_click,
DIV0(COUNT(DISTINCT s.user_id), COUNT(DISTINCT c.user_id)) AS click_to_signup,
DIV0(COUNT(DISTINCT b.user_id), COUNT(DISTINCT s.user_id)) AS signup_to_sub
FROM date_spine ds
LEFT JOIN imp i ON i.d = ds.d
LEFT JOIN clk c ON c.d = ds.d AND c.user_id = i.user_id
LEFT JOIN sgn s ON s.d = ds.d AND s.user_id = c.user_id
LEFT JOIN sub b ON b.d = ds.d AND b.user_id = s.user_id
GROUP BY ds.d
ORDER BY ds.d;
Key design choices:
- Each stage resolves to the first qualifying event per
(user_id, impression_day). This keeps every stage a strict subset of the one before, so rates are bounded by 1. - Do not filter
evto the 7-day window before building stage CTEs. u4's impression on 08-31 converts via a click at 07:30 the next morning — the conversion event lives outside the window. - Use
DIV0(Snowflake) orNULLIF(..., 0)to avoid divide-by-zero on zero-impression days. - Flag recent cohorts as right-censored. A user with an impression on 2025-08-31 has until 2025-09-10 to subscribe. Add
is_complete = (ds.d <= DATEADD(day, -11, CURRENT_DATE))to the output for downstream consumers.
Expected output for sample data:
| day | impressions | clicks_w1d | signups_w3d | subs_w7d |
|---|---|---|---|---|
| 2025-08-26 | 1 | 1 | 1 | 1 |
| 2025-08-30 | 1 | 1 | 1 | 0 |
| 2025-08-31 | 1 | 1 | 1 | 0 |
| 2025-09-01 | 1 | 1 | 0 | 0 |
Part (b) — Median time to first watch by acquisition channel
Signup events carry a NULL campaign_id, so channel must be looked up from prior touchpoints.
, first_signup AS (
SELECT user_id, MIN(event_ts) AS sgn_ts
FROM ev
WHERE event_type = 'signup'
AND event_ts >= '2025-08-01' AND event_ts < '2025-09-01'
GROUP BY user_id
)
, attributed AS (
SELECT
s.user_id,
s.sgn_ts,
(
SELECT MAX_BY(e.campaign_id, e.event_ts)
FROM ev e
WHERE e.user_id = s.user_id
AND e.campaign_id IS NOT NULL
AND e.event_type IN ('impression', 'click')
AND e.event_ts BETWEEN DATEADD(day, -7, s.sgn_ts) AND s.sgn_ts
) AS last_campaign
FROM first_signup s
)
, first_watch AS (
SELECT user_id, MIN(event_ts) AS w_ts
FROM ev
WHERE event_type = 'watch_start'
GROUP BY user_id
)
SELECT
CAST(a.sgn_ts AS DATE) AS signup_date,
IFF(a.last_campaign IS NULL, 'organic', 'paid') AS acquisition_channel,
COUNT(*) AS signups,
COUNT(f.w_ts) AS reached_watch,
MEDIAN(DATEDIFF('minute', a.sgn_ts, f.w_ts)) AS median_min_to_watch
FROM attributed a
LEFT JOIN first_watch f ON f.user_id = a.user_id AND f.w_ts >= a.sgn_ts
GROUP BY 1, 2
ORDER BY 1, 2;
MAX_BY picks the campaign_id associated with the latest pre-signup touchpoint. In BigQuery, replace with ARRAY_AGG(campaign_id ORDER BY event_ts DESC LIMIT 1)[OFFSET(0)].
Part (c) — Suspicious campaign flagging
This part intentionally queries the raw events table, not ev. Deduplication would lower apparent impression counts and might mask the fraud pattern itself.
SELECT
campaign_id,
COUNT(*) AS impressions,
COUNT(*) FILTER (WHERE event_type = 'click') AS clicks,
DIV0(
COUNT(*) FILTER (WHERE event_type = 'click'),
COUNT(*)
) AS ctr,
COUNT(DISTINCT user_id) AS distinct_users
FROM events
WHERE campaign_id IS NOT NULL
AND event_type IN ('impression', 'click')
AND event_ts >= '2025-08-26' AND event_ts <= '2025-09-01'
GROUP BY campaign_id
HAVING COUNT(*) >= 100
AND DIV0(
COUNT(*) FILTER (WHERE event_type = 'click'),
COUNT(*)
) > 0.80
AND COUNT(DISTINCT user_id) <= 5;
The sample data does not satisfy the impressions ≥ 100 threshold, so this returns zero rows — that is expected and worth stating.
Part (e) — 28-day rolling unique viewers, top 3 shows
Pre-aggregate daily uniques first to avoid an O(n²) self-join at scale.
, daily_uniq AS (
SELECT
CAST(event_ts AS DATE) AS dt,
show_id,
COUNT(DISTINCT user_id) AS daily_viewers
FROM ev
WHERE event_type = 'watch_start'
AND event_ts >= '2025-08-01' AND event_ts < '2025-10-01'
GROUP BY 1, 2
)
, rolling AS (
SELECT
a.dt,
a.show_id,
a.daily_viewers,
SUM(b.daily_viewers) AS rolling_28d_viewers -- approximate; see note
FROM daily_uniq a
JOIN daily_uniq b
ON b.show_id = a.show_id
AND b.dt BETWEEN DATEADD(day, -27, a.dt) AND a.dt
GROUP BY a.dt, a.show_id, a.daily_viewers
)
SELECT sh.title, r.rolling_28d_viewers, r.daily_viewers
FROM rolling r
JOIN shows sh ON sh.show_id = r.show_id
WHERE r.dt = '2025-09-01'
ORDER BY r.rolling_28d_viewers DESC, r.daily_viewers DESC
LIMIT 3;
Scaling note: Summing daily uniques is an approximation — a user who watched on multiple days is counted multiple times. For an exact distinct count use APPROX_COUNT_DISTINCT across the raw 28-day window, or use HyperLogLog sketches (HLL_ACCUMULATE / HLL_COMBINE in Snowflake) to merge pre-built daily sketches in O(1) space.
Scaling to billions of rows
| Concern | Recommendation |
|---|---|
| Partition pruning | Cluster/partition events on event_ts (by day or month). Every query above filters on event_ts first. |
| Funnel joins | After dedup, each stage CTE filters to a single event_type. Add a secondary clustering key on (user_id, event_type). |
COUNT(DISTINCT) | Use APPROX_COUNT_DISTINCT or HLL sketches where exact counts are not contractually required; typically within 2% error at 100× the speed. |
| Channel attribution subquery | Convert the correlated subquery in part (b) to a pre-aggregated last-touch CTE to avoid per-row scans. |
| Rolling windows | Pre-aggregate to daily granularity before windowing. Never window over raw event rows. |
Common mistakes to avoid
- Calendar-day comparisons instead of timestamp intervals. "Within 1 day" means
event_ts <= imp_ts + INTERVAL '1 day', notDATE(event_ts) = DATE(imp_ts) + 1. - Anchoring the funnel to only the first impression. A user with multiple impressions in a day should advance if any of them leads to a click within the window.
- Reading
campaign_idoff the signup row. It is always NULL. Channel attribution requires a backward lookup. - Deduplicating before fraud detection. Dedup removes the very signal you are trying to catch.
- Ignoring right-censoring. Recent cohorts look like low converters simply because their conversion windows have not closed yet. Always label or filter incomplete cohorts.