E-commerce Event Aggregation: Metrics and Ranking
SQL & DataModel answerLast updated
Aggregate event logs to compute shop exposure metrics, normalize by observation period, rank within categories using window functions, and segment user engagement by tenure.
You're analyzing event logs from an e-commerce platform. Each row represents one user interaction with a shop on a specific date:
+----------+---------+------------+------------+-------------+--------------+
| user_id | shop_id | event_date | is_visible | signup_date | action_type |
+----------+---------+------------+------------+-------------+--------------+
| 101 | 12 | 2023-06-01 | TRUE | 2023-05-20 | view |
| 102 | 18 | 2023-06-01 | FALSE | 2021-11-02 | view |
| 103 | 44 | 2023-06-02 | TRUE | 2023-06-01 | click |
| 104 | 12 | 2023-06-02 | TRUE | 2020-01-15 | purchase |
| 105 | 18 | 2023-06-02 | FALSE | 2023-05-30 | view |
+----------+---------+------------+------------+-------------+--------------+
Your tasks:
-
Basic aggregation: Count how many distinct calendar dates each shop appeared as visible. Filter to shops with at least one visible day and order by count descending.
-
Rate and categorization: Normalize visibility by dividing visible days by total observed days. Join to a
shopsdimension table (containingshop_idandcategory) and classify each shop into visibility tiers: "High" (≥80%), "Medium" (≥40%), "Low" (>0%), or "Never visible". -
Category ranking: Define a daily visibility score for each shop-day as the fraction of that day's events where the shop was visible. Average this score across all days the shop appeared, then rank shops within their category by this average using a window function.
-
User tenure analysis: Using today's events only, segment users into tenure buckets (0–30 days, 31–365 days, >365 days since signup). Define "active" events as clicks or purchases. Report two metrics per bucket: average active events per user, and the proportion of users with at least one active event.
Write SQL queries for each part. State your assumptions about data grain, edge cases, and metric definitions.
Hints
Hint 1
The data grain is one row per user-event-date, not one row per shop-date. Count distinct dates to avoid inflating totals.
Hint 2
Visibility rate = visible_days / observed_days. Use floating-point division and handle division by zero.
Hint 3
For tenure analysis, aggregate to user level first to get the correct denominator—users, not events.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The critical insight is recognizing the data grain: each row is a user interaction, so multiple rows can exist for the same shop on the same date. Counting rows directly overcounts; you must count distinct dates. The four parts build in complexity, from basic aggregation to window functions and cohort analysis.
Part 1: Count Distinct Visible Dates
Count unique dates where is_visible = TRUE for each shop. Use conditional aggregation to keep all shops in scope, then filter explicitly.
SELECT
shop_id,
COUNT(DISTINCT CASE WHEN is_visible THEN event_date END) AS visible_days
FROM shop_visibility
GROUP BY shop_id
HAVING COUNT(DISTINCT CASE WHEN is_visible THEN event_date END) > 0
ORDER BY visible_days DESC, shop_id;
Why not WHERE is_visible? Filtering before grouping silently drops shops that were never visible. The conditional count keeps all shops, making the HAVING clause explicit and adjustable. For the sample data:
- Shop 12: 2 visible days
- Shop 44: 1 visible day
- Shop 18: 0 visible days (excluded by
HAVING)
Time complexity: O(n) for a single scan with hash aggregation.
Part 2: Normalize and Categorize
Raw counts favor older shops. Compute a visibility rate as visible_days / observed_days, join to dimension data, and bucket.
WITH shop_metrics AS (
SELECT
shop_id,
COUNT(DISTINCT event_date) AS observed_days,
COUNT(DISTINCT CASE WHEN is_visible THEN event_date END) AS visible_days
FROM shop_visibility
GROUP BY shop_id
)
SELECT
m.shop_id,
COALESCE(s.category, 'Unknown') AS category,
m.visible_days,
m.observed_days,
m.visible_days * 1.0 / NULLIF(m.observed_days, 0) AS visibility_rate,
CASE
WHEN m.visible_days * 1.0 / NULLIF(m.observed_days, 0) >= 0.8 THEN 'High'
WHEN m.visible_days * 1.0 / NULLIF(m.observed_days, 0) >= 0.4 THEN 'Medium'
WHEN m.visible_days > 0 THEN 'Low'
ELSE 'Never visible'
END AS visibility_tier
FROM shop_metrics m
LEFT JOIN shops s ON s.shop_id = m.shop_id
ORDER BY m.visible_days DESC;
Key decisions:
LEFT JOINpreserves shops missing from the dimension table* 1.0forces float division in SQL dialects with integer divisionNULLIF(observed_days, 0)prevents division by zero (returns NULL)CASEbranches evaluate top-down, so thresholds must be descending
Part 3: Rank by Average Daily Visibility
Define daily visibility as the proportion of a shop's events that day where it was visible. Average these daily proportions, then rank within category.
WITH daily_scores AS (
SELECT
shop_id,
event_date,
AVG(CASE WHEN is_visible THEN 1.0 ELSE 0.0 END) AS daily_visibility
FROM shop_visibility
GROUP BY shop_id, event_date
),
shop_averages AS (
SELECT
d.shop_id,
COALESCE(s.category, 'Unknown') AS category,
AVG(d.daily_visibility) AS avg_visibility,
COUNT(DISTINCT d.event_date) AS days_observed
FROM daily_scores d
LEFT JOIN shops s ON s.shop_id = d.shop_id
GROUP BY d.shop_id, COALESCE(s.category, 'Unknown')
)
SELECT
category,
shop_id,
avg_visibility,
days_observed,
DENSE_RANK() OVER (
PARTITION BY category
ORDER BY avg_visibility DESC
) AS category_rank
FROM shop_averages
WHERE days_observed >= 3 -- filter noise from single-day shops
ORDER BY category, category_rank;
Ranking function choice:
DENSE_RANK(): tied shops get the same rank, no gapsRANK(): leaves gaps after ties (rank 1, 1, 3)ROW_NUMBER(): breaks ties arbitrarily without a secondary sort key
A shop seen once can rank first by luck. The WHERE days_observed >= 3 filter removes noise; adjust threshold based on business needs.
Complexity: O(n) for the first aggregation, O(m log m) for ranking m shops per category.
Part 4: User Tenure Segmentation
Metric definition (always state before coding):
- Snapshot: events where
event_date = CURRENT_DATE - Tenure: days since signup (
DATEDIFF(CURRENT_DATE, signup_date)) - Active event:
clickorpurchase(views are passive) - Metrics: active events per user, and active user rate per tenure bucket
Aggregate to user level first to get correct denominators.
WITH todays_events AS (
SELECT
user_id,
DATEDIFF(CURRENT_DATE, signup_date) AS tenure_days,
action_type
FROM shop_visibility
WHERE event_date = CURRENT_DATE
),
user_summary AS (
SELECT
user_id,
MAX(tenure_days) AS tenure,
SUM(CASE WHEN action_type IN ('click', 'purchase') THEN 1 ELSE 0 END) AS active_events
FROM todays_events
GROUP BY user_id
),
bucketed_users AS (
SELECT
CASE
WHEN tenure <= 30 THEN 'New (0-30d)'
WHEN tenure <= 365 THEN 'Established (31-365d)'
ELSE 'Veteran (365d+)'
END AS tenure_bucket,
active_events
FROM user_summary
)
SELECT
tenure_bucket,
COUNT(*) AS total_users,
SUM(active_events) AS total_active_events,
SUM(active_events) * 1.0 / COUNT(*) AS active_events_per_user,
AVG(CASE WHEN active_events > 0 THEN 1.0 ELSE 0.0 END) AS active_user_rate
FROM bucketed_users
GROUP BY tenure_bucket
ORDER BY
CASE tenure_bucket
WHEN 'New (0-30d)' THEN 1
WHEN 'Established (31-365d)' THEN 2
ELSE 3
END;
Why user-level aggregation? If you bucket at the event level, COUNT(*) counts events instead of users, making the denominator wrong. Rolling up to one row per user ensures correct per-user metrics.
Two metrics for robustness: Events per user can be skewed by power users. Active user rate (proportion with ≥1 active event) is bounded in [0,1] and complements the first metric.
Common Mistakes
- Counting rows instead of distinct dates: Overcounts by the number of users per shop-day
- Integer division:
visible_days / observed_daysreturns 0 in many SQL dialects without* 1.0 - Wrong window partition: Forgetting
PARTITION BY categoryranks all shops together - Event-level tenure bucketing: Gets user counts wrong by counting events
- Ignoring zero-day shops: Using
INNER JOINsilently drops shops missing from the dimension
Complexity
- Part 1–2: O(n) with hash aggregation
- Part 3: O(n + m log m) where m = shops per category
- Part 4: O(n) for aggregation, O(k) for final grouping where k = number of buckets
All queries execute in a single pass over the data with standard SQL optimizations.