KatInterview

Aggregate Session Time by Category Over a Rolling Week

SQL & DataModel answer
MediumModel answerSQL & Datasqldata-analysisaggregation

Last 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 occurred
  • app_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 days through :target_date.
  • Merge session data with the applications table to retrieve each app's category.
  • When an app_id doesn't exist in applications, or when category is 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 category
  • percentage — 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.