KatInterview

E-commerce Event Aggregation: Metrics and Ranking

SQL & DataModel answer
MediumModel answerSQL & Dataaggregationwindow-functionsjoins

Last 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:

  1. 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.

  2. Rate and categorization: Normalize visibility by dividing visible days by total observed days. Join to a shops dimension table (containing shop_id and category) and classify each shop into visibility tiers: "High" (≥80%), "Medium" (≥40%), "Low" (>0%), or "Never visible".

  3. 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.

  4. 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.