Aggregate Session Time by Category Over a Rolling Week
SQL & DataModel answerLast updated
Calculate the percentage of total usage time for each application category across the most recent seven days of user sessions.
You're building analytics for a VR platform's engagement dashboard.
Schema
You have two tables:
session_log
user_id(BIGINT)session_date(DATE) — the calendar day when the session occurredapp_id(INT)session_id(VARCHAR)time_seconds(INT) — how long the session lasted
applications
app_id(INT, primary key)name(VARCHAR)category(VARCHAR) — may be NULL for some apps
The session_log.app_id references applications.app_id.
Your Task
Given a reference date parameter :target_date, calculate what percentage of total session time falls into each application category during the seven-day period ending on that date (inclusive).
Specifications
- Include all seven days: from
:target_date - 6 daysthrough:target_date. - Merge session data with the applications table to retrieve each app's category.
- When an
app_iddoesn't exist inapplications, or whencategoryis NULL, group those sessions under'Uncategorized'. - Calculate percentage as: (time in category) / (total time across all categories).
Output Format
Return one row per category with these columns:
category— the category name (or'Uncategorized')total_seconds— sum of session time for this categorypercentage— share of total time, expressed as a number between 0 and 100
Hints
Hint 1
Use a LEFT JOIN to preserve sessions even when the app isn't found in the applications table.
Hint 2
Compute the denominator using a window function over the aggregated results to avoid a separate scan.
Hint 3
Watch for the date range: 7 days inclusive means subtracting 6, not 7.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Rolling-Week Session Time by Category
Approach
This problem tests your ability to filter, join, aggregate, and normalize data in a single pipeline. The core steps are:
- Filter sessions to the seven-day window:
[target_date - 6, target_date]. This captures exactly seven calendar days. - Preserve unmatched sessions with a LEFT JOIN to
applications. Using an INNER JOIN would silently discard sessions for apps not in the lookup table, skewing the percentages. - Normalize missing categories by coalescing NULL or missing category values into a single label,
'Uncategorized'. - Aggregate total seconds per category.
- Compute percentages by dividing each category's total by the grand total. Use a window function to calculate the grand total in one pass.
SQL Solution
The solution below returns percentage on a 0–100 scale, rounded to two decimal places.
WITH recent_sessions AS (
SELECT
sl.app_id,
sl.time_seconds
FROM session_log sl
WHERE sl.session_date BETWEEN :target_date::DATE - INTERVAL '6 days'
AND :target_date::DATE
AND sl.time_seconds IS NOT NULL
AND sl.time_seconds > 0
),
category_totals AS (
SELECT
COALESCE(app.category, 'Uncategorized') AS category,
SUM(rs.time_seconds)::BIGINT AS total_seconds
FROM recent_sessions rs
LEFT JOIN applications app USING (app_id)
GROUP BY COALESCE(app.category, 'Uncategorized')
)
SELECT
category,
total_seconds,
ROUND(
100.0 * total_seconds / NULLIF(SUM(total_seconds) OVER (), 0),
2
) AS percentage
FROM category_totals
ORDER BY total_seconds DESC;
Python Implementation
Interviewers often ask for a pandas version as a follow-up:
import pandas as pd
def session_time_by_category(
session_log: pd.DataFrame,
applications: pd.DataFrame,
target_date: str
) -> pd.DataFrame:
"""Return category totals and percentages for the 7 days ending on target_date."""
end_date = pd.Timestamp(target_date).normalize()
start_date = end_date - pd.Timedelta(days=6)
sessions = session_log.copy()
sessions['session_date'] = pd.to_datetime(sessions['session_date']).dt.normalize()
sessions = sessions[
(sessions['session_date'] >= start_date) &
(sessions['session_date'] <= end_date) &
(sessions['time_seconds'].notna()) &
(sessions['time_seconds'] > 0)
]
merged = sessions.merge(
applications[['app_id', 'category']],
on='app_id',
how='left'
)
merged['category'] = merged['category'].fillna('Uncategorized')
result = (
merged.groupby('category', as_index=False)['time_seconds']
.sum()
.rename(columns={'time_seconds': 'total_seconds'})
)
grand_total = result['total_seconds'].sum()
result['percentage'] = (
(100.0 * result['total_seconds'] / grand_total).round(2)
if grand_total > 0 else 0.0
)
return result.sort_values('total_seconds', ascending=False).reset_index(drop=True)
Why This Works
- Inclusive 7-day range: Subtracting 6 days from the target gives you 7 distinct dates. Subtracting 7 would give you 8 days—a classic off-by-one error.
- LEFT JOIN preserves all sessions. Since
app_idis a primary key inapplications, the join doesn't create duplicates. If it weren't unique, you'd need to deduplicate first. - Single aggregation pass. The window function
SUM(...) OVER ()computes the denominator from the already-aggregated category totals, ensuring numerator and denominator use identical filters. - Unified NULL handling. Grouping by
COALESCE(category, 'Uncategorized')merges two scenarios—apps missing from the table and apps with NULL category—into one bucket. - Floating-point division. Multiplying by
100.0(not100) prevents integer truncation.
Complexity
- Time: O(N) to scan and filter sessions, O(M) to build a hash table for the join on
applications, O(N) to aggregate. Sorting K categories costs O(K log K), which is negligible since K is small. An index onsession_datereduces the scan to just seven days of data. - Space: O(M) for the join hash table, O(K) for category aggregates.
Edge Cases & Trade-offs
| Scenario | How to Handle |
|---|---|
App not in applications table | LEFT JOIN ensures it's kept; COALESCE labels it 'Uncategorized' |
App exists but category is NULL | Same 'Uncategorized' bucket (mention you chose to merge these) |
| No sessions in the 7-day window | Zero rows returned; NULLIF prevents divide-by-zero |
| All time values are zero | NULLIF makes percentage NULL instead of erroring |
NULL or negative time_seconds | Filter them out; SUMs would ignore NULLs anyway, but explicit filtering clarifies intent |
| Integer overflow on SUM | Cast to BIGINT if session volumes are large |
Partial data on target_date | That day may be incomplete; ask whether the business wants 7 complete days (using target_date - 1 as the end) |
| Duplicate session records | Not deduped here; confirm whether session_id is unique per day/app. If duplicates exist, dedupe on (session_id, session_date, app_id) first |
| Sessions crossing midnight | Attributed to session_date as recorded; note this as a data model assumption |
What Interviewers Look For
- Choosing LEFT JOIN over INNER JOIN. This is the primary trap. An inner join drops unmatched sessions and inflates every other category's share.
- Correct date arithmetic. Stating the range precisely (7 days inclusive) and avoiding off-by-one errors.
- Explicit handling of NULLs. A single, clearly labeled bucket for missing or unknown categories.
- Window function fluency. Using
SUM(...) OVER ()to compute the denominator cleanly, without a self-join or correlated subquery. - Data quality awareness. Asking about duplicate sessions, negative durations, timezones (UTC is specified here, but strong candidates ask whether users expect local-time day boundaries), and whether the target date is partial.
- Percentage scale clarity. Stating whether you're returning 0–1 or 0–100, and avoiding integer division.
Common Follow-Up
"Now break this down per user segment or per day."
Add the new dimension to the GROUP BY, and change the window function to PARTITION BY that dimension, so each slice independently sums to 100%.