Compute Daily Conversion and User Order History with Deduplication
SQL & DataModel answerLast updated
Write SQL to calculate daily conversion metrics and per-user order summaries over a week, handling event deduplication and missing days.
You are analyzing user behavior for an e-commerce platform. All timestamps are stored in UTC. For this exercise, assume "today" is 2025-09-01, and you need to analyze the past seven days: the inclusive range from 2025-08-26 00:00:00 through 2025-09-01 23:59:59.
You have three tables:
users
user_id(INT, primary key)signup_at(TIMESTAMP)tz(STRING, user's timezone)
orders
order_id(INT, primary key)user_id(INT, foreign key)order_ts(TIMESTAMP)amount(DECIMAL(10,2))status(STRING, either 'completed' or 'canceled')
events
event_id(INT, primary key)user_id(INT, foreign key)event_ts(TIMESTAMP)event_type(STRING, e.g., 'view_product', 'add_to_cart', 'purchase')product_id(INT)device_id(STRING)
Sample data is provided below:
users
user_id | signup_at | tz
1 | 2025-08-10 09:00:00 | America/Los_Angeles
2 | 2025-08-28 14:00:00 | UTC
3 | 2025-08-30 23:30:00 | America/New_York
orders
order_id | user_id | order_ts | amount | status
101 | 1 | 2025-08-27 23:55:00 | 20.00 | completed
102 | 1 | 2025-08-28 00:05:00 | 15.00 | canceled
103 | 2 | 2025-08-31 12:00:00 | 9.99 | completed
104 | 2 | 2025-09-01 00:00:10 | 49.00 | completed
105 | 3 | 2025-08-26 23:59:59 | 5.00 | completed
events
event_id | user_id | event_ts | event_type | product_id | device_id
1 | 1 | 2025-08-27 23:50:00 | view_product | 555 | A
2 | 1 | 2025-08-27 23:50:00 | view_product | 555 | A
3 | 1 | 2025-08-28 00:03:00 | add_to_cart | 555 | A
4 | 1 | 2025-08-28 00:04:00 | purchase | 555 | A
5 | 2 | 2025-08-31 11:58:00 | view_product | 777 | B
6 | 3 | 2025-08-26 23:55:00 | view_product | 999 | C
7 | 3 | 2025-08-26 23:58:00 | purchase | 999 | C
8 | 2 | 2025-09-01 00:00:10 | purchase | 777 | B
Notice that events 1 and 2 are exact duplicates.
Your tasks:
Write Standard SQL (CTEs are allowed) to produce two result sets:
-
Daily conversion metrics: For each day in the seven-day window, calculate:
unique_viewers: count of distinct users who had at least oneview_productevent that day (after deduplicating exact duplicate events)purchasers: count of completed orders placed that day (exclude canceled orders)conversion_rate:purchasers / unique_viewers(handle division by zero gracefully)
Include all seven days in the output, even if some days have zero activity. Order by day ascending.
-
User-level order summary: For each user in the
userstable, compute:first_completed_order_ts: timestamp of their earliest completed order in the window (NULL if none)last_completed_order_ts: timestamp of their latest completed order in the window (NULL if none)total_completed_orders: count of completed orders in the window
Use window functions rather than correlated subqueries. Order by
user_idascending.
Deduplication rule: Treat rows in events as duplicates if they share identical values for (user_id, event_ts, event_type, product_id, device_id). Keep only one representative row per duplicate group.
Notes:
- Only completed orders count as purchases; ignore canceled orders entirely
- All date calculations use UTC day boundaries
- Since SQL returns one result set per query, you may present both queries sharing the same CTE block, or describe how you'd run them sequentially
Bonus: Sketch a Pandas solution for the daily metrics and deduplication logic.
Hints
Hint 1
Generate a date spine for all seven days to ensure days with zero activity still appear in the output.
Hint 2
Deduplicate events using ROW_NUMBER partitioned by the full duplicate key before performing any aggregations.
Hint 3
When joining users to orders, filter orders in the CTE or ON clause—not in WHERE—to preserve users with no completed orders.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests several intermediate SQL patterns that often trip up candidates:
1. Event deduplication before aggregation
Use ROW_NUMBER() partitioned by the full duplicate key (user_id, event_ts, event_type, product_id, device_id) and keep rows where rn = 1. While COUNT(DISTINCT user_id) might seem sufficient here, explicit deduplication is part of the requirement and generalizes to metrics that need accurate event counts.
2. Complete date spine
Days with zero views or orders (like 2025-08-28 through 2025-08-30 in the sample) must still appear. Generate all seven dates using a recursive CTE or GENERATE_DATE_ARRAY, then LEFT JOIN the aggregates.
3. Precise window boundaries
Use a half-open interval [2025-08-26, 2025-09-02) rather than <= '2025-09-01 23:59:59'. The closed form silently drops rows with fractional seconds at the boundary.
4. Preserve all users in the user-level query
Start from the users table and LEFT JOIN to filtered orders. If you filter in the WHERE clause after the join, users with no orders disappear. Put the filter in the ON clause or pre-filter in a CTE.
5. Window functions for user aggregates
Compute MIN(order_ts), MAX(order_ts), and COUNT(order_id) as window functions partitioned by user_id, then collapse to one row per user with ROW_NUMBER() or DISTINCT.
SQL Solution
WITH RECURSIVE days (d) AS (
SELECT CAST('2025-08-26' AS DATE)
UNION ALL
SELECT CAST(d + INTERVAL '1' DAY AS DATE)
FROM days
WHERE d < CAST('2025-09-01' AS DATE)
),
deduped_events AS (
SELECT *
FROM (
SELECT e.*,
ROW_NUMBER() OVER (
PARTITION BY user_id, event_ts, event_type, product_id, device_id
ORDER BY event_id
) AS rn
FROM events e
) x
WHERE rn = 1
),
completed_orders_in_window AS (
SELECT *
FROM orders
WHERE status = 'completed'
AND order_ts >= TIMESTAMP '2025-08-26 00:00:00'
AND order_ts < TIMESTAMP '2025-09-02 00:00:00'
),
daily_viewers AS (
SELECT CAST(event_ts AS DATE) AS day,
COUNT(DISTINCT user_id) AS unique_viewers
FROM deduped_events
WHERE event_type = 'view_product'
AND event_ts >= TIMESTAMP '2025-08-26 00:00:00'
AND event_ts < TIMESTAMP '2025-09-02 00:00:00'
GROUP BY CAST(event_ts AS DATE)
),
daily_purchasers AS (
SELECT CAST(order_ts AS DATE) AS day,
COUNT(*) AS purchasers
FROM completed_orders_in_window
GROUP BY CAST(order_ts AS DATE)
),
user_order_windows AS (
SELECT u.user_id,
MIN(o.order_ts) OVER (PARTITION BY u.user_id) AS first_completed_order_ts,
MAX(o.order_ts) OVER (PARTITION BY u.user_id) AS last_completed_order_ts,
COUNT(o.order_id) OVER (PARTITION BY u.user_id) AS total_completed_orders,
ROW_NUMBER() OVER (PARTITION BY u.user_id ORDER BY o.order_ts) AS rn
FROM users u
LEFT JOIN completed_orders_in_window o ON o.user_id = u.user_id
)
-- Query 1: Daily conversion metrics
SELECT d.d AS day,
COALESCE(v.unique_viewers, 0) AS unique_viewers,
COALESCE(p.purchasers, 0) AS purchasers,
CAST(COALESCE(p.purchasers, 0) AS DECIMAL(18,6))
/ NULLIF(COALESCE(v.unique_viewers, 0), 0) AS conversion_rate
FROM days d
LEFT JOIN daily_viewers v ON v.day = d.d
LEFT JOIN daily_purchasers p ON p.day = d.d
ORDER BY day;
-- Query 2: User-level order summary (share the same CTE block)
-- SELECT user_id,
-- first_completed_order_ts,
-- last_completed_order_ts,
-- total_completed_orders
-- FROM user_order_windows
-- WHERE rn = 1
-- ORDER BY user_id;
Since a single SQL statement returns one result set, present both queries sharing the CTE block or run them sequentially as separate statements. Mentioning this constraint demonstrates understanding of SQL execution.
Expected Output
Daily metrics:
day | unique_viewers | purchasers | conversion_rate
2025-08-26 | 1 | 1 | 1.000000
2025-08-27 | 1 | 1 | 1.000000
2025-08-28 | 0 | 0 | NULL
2025-08-29 | 0 | 0 | NULL
2025-08-30 | 0 | 0 | NULL
2025-08-31 | 1 | 1 | 1.000000
2025-09-01 | 0 | 1 | NULL
User-level summary:
user_id | first_completed_order_ts | last_completed_order_ts | total_completed_orders
1 | 2025-08-27 23:55:00 | 2025-08-27 23:55:00 | 1
2 | 2025-08-31 12:00:00 | 2025-09-01 00:00:10 | 2
3 | 2025-08-26 23:59:59 | 2025-08-26 23:59:59 | 1
Why It Works
- Deduplication: Events 1 and 2 collapse into one row, so user 1 counts once on 2025-08-27
- Day boundaries: Casting UTC timestamps to
DATEcorrectly assigns orders to their respective days - Canceled orders excluded: Order 102 doesn't count, so 2025-08-28 shows 0 purchasers
- Division by zero:
NULLIFprevents errors whenunique_viewersis 0; result is NULL rather than infinity - Zero-order users:
COUNT(o.order_id)counts only matched rows, giving 0 for users with no orders (with NULL timestamps) - Complete date range: The spine ensures all seven days appear even when activity is sparse
Complexity
- Time: O(E log E) for event deduplication, O(E + O) for daily aggregates, O((U + O) log(U + O)) for user-level windows
- Space: O(E + O + U) for intermediate CTEs
In production, push the window filter into deduped_events to enable partition pruning in columnar engines like Snowflake or BigQuery.
Common Mistakes
- Forgetting the date spine: Missing days disappear from the output
- Filtering after LEFT JOIN: Putting
status = 'completed'inWHEREinstead ofONeliminates users with no orders - Using
COUNT(*)instead ofCOUNT(column): Returns 1 for unmatched left-join rows instead of 0 - Closed-interval boundaries:
<= '23:59:59'misses fractional-second timestamps - Integer division:
1/2becomes 0 in many SQL dialects; cast to decimal first
Pandas Sketch (Bonus)
import pandas as pd
START = pd.Timestamp("2025-08-26")
END = pd.Timestamp("2025-09-02") # exclusive
def compute_metrics(users, orders, events):
# Parse timestamps
events["event_ts"] = pd.to_datetime(events["event_ts"])
orders["order_ts"] = pd.to_datetime(orders["order_ts"])
# Deduplicate events
dedup_keys = ["user_id", "event_ts", "event_type", "product_id", "device_id"]
events_dedup = (events.sort_values("event_id")
.drop_duplicates(subset=dedup_keys, keep="first"))
# Filter to window
views = events_dedup[
(events_dedup["event_type"] == "view_product") &
(events_dedup["event_ts"] >= START) &
(events_dedup["event_ts"] < END)
]
completed = orders[
(orders["status"] == "completed") &
(orders["order_ts"] >= START) &
(orders["order_ts"] < END)
]
# Daily metrics
days = pd.date_range(START, END - pd.Timedelta(days=1), freq="D")
daily_viewers = (views.assign(day=views["event_ts"].dt.date)
.groupby("day")["user_id"]
.nunique()
.reindex(days.date, fill_value=0))
daily_purchasers = (completed.assign(day=completed["order_ts"].dt.date)
.groupby("day").size()
.reindex(days.date, fill_value=0))
daily_metrics = pd.DataFrame({
"day": days.date,
"unique_viewers": daily_viewers.values,
"purchasers": daily_purchasers.values
})
daily_metrics["conversion_rate"] = (daily_metrics["purchasers"] /
daily_metrics["unique_viewers"].replace(0, pd.NA))
return daily_metrics
This demonstrates the key operations: explicit deduplication with drop_duplicates, windowing with boolean indexing, and spine generation with reindex.