Top Content Category by Country and Weekly Power-User Share
SQL & DataModel answerLast updated
Write SQL to find each country's top-impression category and the share of weekly active users who were active on 4+ days and used 3+ distinct features on a single day.
Context
You are an analyst at a worldwide content platform. The team wants a view of how impressions and engagement break down by country over the most recent week. You have three tables.
impressions (assume already limited to the week under study)
| user_id | country | category | impression_cnt |
|---|---|---|---|
| 1 | US | Sports | 120 |
| 2 | US | News | 80 |
| 3 | CN | Games | 200 |
user_activity (one row per user per day on which they were active; duplicates are possible)
| user_id | activity_dt |
|---|---|
| 1 | 2023-09-01 |
| 1 | 2023-09-02 |
| 1 | 2023-09-04 |
| 2 | 2023-09-01 |
| 3 | 2023-09-05 |
feature_usage (one row per feature used by a user on a given day)
| user_id | usage_dt | feature |
|---|---|---|
| 1 | 2023-09-02 | search |
| 1 | 2023-09-02 | share |
| 1 | 2023-09-02 | save |
| 2 | 2023-09-03 | search |
| 3 | 2023-09-05 | save |
Tasks
(a) For every country, return the content category with the largest total impressions, along with that total.
(b) Compute the weekly power-user rate. A power user is someone who:
- was active on at least 4 distinct days within the last 7 days, and
- on at least one of those active days, used at least 3 distinct features.
The rate is power users divided by users who were active at least once in the window.
What to deliver
- Two SQL queries (any mainstream dialect is fine).
- A short list of the assumptions you made (window definition, tie handling, denominator, NULLs).
- A note on how you avoid inflated counts when combining tables that have many rows per user.
- Expected output on the sample data, assuming the window ends on 2023-09-07.
Hints
Hint 1
For (a), sum impressions to the (country, category) level first, then rank within each country using a window function partitioned by country.
Hint 2
For (b), do not join user_activity and feature_usage directly and count. Reduce each to its natural grain first: distinct (user, day) pairs, and per-(user, day) distinct feature counts.
Hint 3
Compute two user-level flags separately (4+ active days; at least one active day with 3+ distinct features), then combine them with a LEFT JOIN and divide by weekly active users, guarding against a zero denominator.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach overview
Treat the two parts as independent problems.
- (a) Aggregate to
(country, category), rank within each country, keep rank 1. - (b) Build two user-level conditions at their own grain, then combine them. Do not join all three tables in one go.
user_activityandfeature_usageboth have many rows per user, so a raw join multiplies rows and inflates any plainCOUNT.
Assumptions to state
- Window: the last 7 days means
[end - 6, end]inclusive, i.e. 7 calendar days. UseCURRENT_DATEin production, or a parameter for reproducible runs. - Impressions have no date: assume the table is already scoped to the week. If there were an impression date, apply the same filter.
- Ties in (a):
RANK()returns all tied categories. If exactly one row per country is required, useROW_NUMBER()with a deterministic tiebreaker such as category name. - Denominator in (b): weekly active users (at least one active day in the window). The alternative, all registered users, dilutes the metric with dormant accounts.
- "On one of those days": the 3-feature day must be one of the user's active days, so feature usage is joined to active days rather than just date-filtered.
- NULLs: decide whether a NULL country or category becomes "Unknown" or is filtered out.
Part (a): top category per country
WITH country_category AS (
SELECT country, category, SUM(impression_cnt) AS total_impressions
FROM impressions
GROUP BY country, category
),
ranked AS (
SELECT country, category, total_impressions,
RANK() OVER (PARTITION BY country
ORDER BY total_impressions DESC) AS rnk
FROM country_category
)
SELECT country, category, total_impressions
FROM ranked
WHERE rnk = 1
ORDER BY country;
Summing first handles several rows per (country, category), for example one row per user. PARTITION BY country ranks each country independently.
Sample result: CN | Games | 200 and US | Sports | 120.
Part (b): weekly power-user rate
WITH params AS (
SELECT CURRENT_DATE - 6 AS start_dt, CURRENT_DATE AS end_dt
),
active_days AS ( -- one row per (user, day) in window
SELECT DISTINCT ua.user_id, ua.activity_dt
FROM user_activity ua
CROSS JOIN params p
WHERE ua.activity_dt BETWEEN p.start_dt AND p.end_dt
),
user_day_counts AS ( -- one row per weekly active user
SELECT user_id, COUNT(*) AS active_day_cnt
FROM active_days
GROUP BY user_id
),
multi_feature_users AS ( -- users with a 3+ feature active day
SELECT DISTINCT fu.user_id
FROM feature_usage fu
JOIN active_days ad
ON ad.user_id = fu.user_id
AND ad.activity_dt = fu.usage_dt
GROUP BY fu.user_id, fu.usage_dt
HAVING COUNT(DISTINCT fu.feature) >= 3
),
flags AS (
SELECT u.user_id,
CASE WHEN u.active_day_cnt >= 4
AND m.user_id IS NOT NULL THEN 1 ELSE 0 END AS is_power
FROM user_day_counts u
LEFT JOIN multi_feature_users m ON m.user_id = u.user_id
)
SELECT COUNT(*) AS weekly_active_users,
SUM(is_power) AS power_users,
ROUND(1.0 * SUM(is_power) / NULLIF(COUNT(*), 0), 4) AS power_user_rate
FROM flags;
Why it is correct
active_daysis deduplicated to(user, day), soCOUNT(*)equals the number of distinct active days. Duplicate activity rows cannot inflate it.- The feature test is evaluated per
(user, day)withCOUNT(DISTINCT feature). Usingsearchfive times on one day counts once, and features spread over several days are never pooled (2 + 2 does not qualify). - Joining feature usage to
active_daysenforces that the qualifying day is an active day. - The two conditions are combined only at user grain through a
LEFT JOIN, so nothing fans out and users without a qualifying day stay in the denominator. 1.0 *avoids integer division, andNULLIFreturns NULL instead of an error for an empty week.
Sanity check on the sample (window ends 2023-09-07)
- User 1: 3 active days. Used 3 features on 09-02, but fails the 4-day rule.
- User 2: 1 active day. Feature use on 09-03 is not on an active day.
- User 3: 1 active day.
Result: 0 power users out of 3 weekly active users, rate 0.0.
Complexity
With hash aggregation each GROUP BY / DISTINCT is linear, so the total is about O(I + A + F) for the three tables. Sort-based plans give O(n log n). The window in (a) sorts within each country. Space is O(country-category groups) for (a) and O(distinct user-day pairs) for (b). Index (user_id, activity_dt) and (user_id, usage_dt), or partition by date, so the window filter prunes early.
Edge cases and common mistakes
- Fan-out: joining
user_activitytofeature_usageand usingCOUNT(*)or evenCOUNT(DISTINCT activity_dt)after other joins is the classic bug. Pre-aggregate instead. - Pooling features across days: counting distinct features per user over the week instead of per day is wrong.
- Timestamps and time zones: cast to date and be explicit; a global product should use UTC or each user's local date.
- Boundary off-by-one:
BETWEEN CURRENT_DATE - 7 AND CURRENT_DATEcovers 8 days. - Ties and NULLs in (a): explain your
RANKvsROW_NUMBERchoice and NULL handling. - Wrong denominator: dividing by all users or by users with impressions changes the metric. State your choice.
Follow-ups to be ready for
- Top two categories per country: change the filter to
rnk <= 2, usingDENSE_RANKif ties should not consume a slot. - Rank by an engagement rate instead of raw impressions: compute the ratio at the
(country, category)grain from summed numerators and denominators, not by averaging per-user ratios. - Rolling 7-day rate for each date: build a calendar table and join each date to its trailing window, or use a windowed approach over a per-user-per-day table.
pandas equivalent for (a)
agg = (impressions.groupby(["country", "category"], as_index=False)["impression_cnt"]
.sum().rename(columns={"impression_cnt": "total_impressions"}))
mx = agg.groupby("country")["total_impressions"].transform("max")
top = agg[agg["total_impressions"] == mx].sort_values("country")
Keeping rows equal to the per-country maximum preserves ties, mirroring RANK.