SQL Analysis and Statistical Testing of App Usage Patterns
SQL & DataModel answerLast updated
Write SQL queries to identify top apps and compute category distributions, then design a statistical test to compare engagement frequency across user segments.
You have a table tracking application usage on a VR platform:
AppUsage
+---------+--------+-----------+--------------+------------+
| user_id | app_id | category | minutes_spent| usage_date |
+---------+--------+-----------+--------------+------------+
| 101 | 12 | Social | 45 | 2023-04-15 |
| 102 | 17 | Game | 30 | 2023-04-16 |
| 101 | 17 | Game | 20 | 2023-04-17 |
| 103 | 22 | Fitness | 25 | 2023-04-17 |
| 104 | 12 | Social | 60 | 2023-04-18 |
+---------+--------+-----------+--------------+------------+
Your task has three parts:
-
Write a SQL query to identify which application accumulated the most total usage time during the most recent 30-day period.
-
Write a SQL query to calculate what proportion of overall usage time each category represents over the same 30-day window.
-
Describe an approach to test whether users who engage with Social apps demonstrate more consistent usage patterns compared to users who engage with Game apps. Specify the metric you would use, the statistical method, and any important considerations.
For date filtering, assume "the past 30 days" means the 30 complete calendar days before today, excluding today's incomplete data.
Hints
Hint 1
Consider how to handle tied results when identifying the top application
Hint 2
Use window functions to calculate totals across the entire result set without self-joins
Hint 3
Think about what 'consistency' means operationally—is it about frequency of visits or duration per visit?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests three distinct skills: time-windowed aggregation, proportional calculations using window functions, and designing a valid statistical comparison. I'll address each part systematically.
Part 1: Identifying the Highest-Usage Application
Strategy: Filter records to the target time window, sum usage by application, and rank the results. A critical consideration is handling ties—multiple applications might share the maximum usage.
WITH windowed_data AS (
SELECT app_id, minutes_spent
FROM AppUsage
WHERE usage_date >= CURRENT_DATE - INTERVAL '30 days'
AND usage_date < CURRENT_DATE
),
aggregated AS (
SELECT app_id,
SUM(minutes_spent) AS total_usage
FROM windowed_data
GROUP BY app_id
),
with_ranking AS (
SELECT app_id,
total_usage,
DENSE_RANK() OVER (ORDER BY total_usage DESC) AS rank
FROM aggregated
)
SELECT app_id, total_usage
FROM with_ranking
WHERE rank = 1;
Why this works: Using DENSE_RANK() ensures that if multiple applications tie for the highest usage, all are returned. A simpler ORDER BY ... LIMIT 1 approach would arbitrarily select one, which might not reflect the actual data. The date filter explicitly excludes today to avoid incomplete data skewing results.
Complexity: O(n) for filtering and aggregation, where n is the number of rows in the table.
Part 2: Computing Category Proportions
Strategy: Aggregate usage by category, then calculate each category's share of the total. The key technique is using a window function to compute the grand total without requiring a second pass or self-join.
WITH windowed_data AS (
SELECT category, minutes_spent
FROM AppUsage
WHERE usage_date >= CURRENT_DATE - INTERVAL '30 days'
AND usage_date < CURRENT_DATE
AND minutes_spent IS NOT NULL
)
SELECT category,
SUM(minutes_spent) AS total_minutes,
ROUND(100.0 * SUM(minutes_spent) /
SUM(SUM(minutes_spent)) OVER (), 2) AS percentage
FROM windowed_data
GROUP BY category
ORDER BY percentage DESC;
Critical details:
SUM(SUM(minutes_spent)) OVER ()computes the grand total across all grouped rows in a single pass- The
100.0literal forces floating-point division; without it, integer division would yield zero - The NULL filter prevents issues with missing data
Sample output (assuming all example rows fall within the window, totaling 180 minutes):
| category | total_minutes | percentage |
|---|---|---|
| Social | 105 | 58.33 |
| Game | 50 | 27.78 |
| Fitness | 25 | 13.89 |
Part 3: Testing Engagement Consistency
Defining the metric: "Consistency" differs from "intensity." While total minutes measures how much users engage, consistency measures how regularly they return. I would use distinct active days per user within the 30-day window as the primary metric. Alternative metrics include sessions per week or median inter-session gaps.
Unit of analysis: The comparison must operate at the user level, not the session level. Sessions within a user are correlated, so treating each row as independent would violate test assumptions and inflate statistical significance.
Handling multi-category users: Users might engage with both Social and Game apps. Two valid approaches:
- Paired comparison: For users active in both categories, compare their Social active days vs. Game active days using a paired test (Wilcoxon signed-rank)
- Independent comparison: Compare users who exclusively use Social vs. those who exclusively use Game using an independent-samples test
Statistical method: For independent samples, I would use the Mann-Whitney U test (also called Wilcoxon rank-sum). This test is appropriate because:
- Active days is a bounded count variable (1-30) with likely skew
- It makes no normality assumptions
- It tests whether one distribution is stochastically larger than another
Hypotheses:
- H₀: Social and Game users have the same distribution of active days
- H₁: Social users have more active days (one-tailed test)
Implementation considerations:
-
Effect size matters: With large datasets, even tiny differences become statistically significant. Report the difference in mean or median active days alongside the p-value.
-
Confidence intervals: Use bootstrapping to construct a confidence interval around the difference in means for interpretability.
-
Confounding variables: This is observational data. Users self-select into categories, so any difference might reflect pre-existing traits (age, tenure, device type) rather than the category itself. Control for this with:
- Regression models including covariates
- Propensity score matching
- Or ideally, a randomized experiment
-
Selection bias: Only users with at least one session appear in the data. New users or those at the edge of the window might have artificially low active-day counts.
Python implementation sketch:
import pandas as pd
from scipy import stats
def test_engagement_consistency(df, start_date, end_date):
# Filter to window
mask = (df['usage_date'] >= start_date) & (df['usage_date'] < end_date)
windowed = df[mask]
# Count active days per user per category
active_days = (windowed.groupby(['user_id', 'category'])['usage_date']
.nunique()
.unstack(fill_value=0))
# Extract exclusive users
social_users = active_days[(active_days['Social'] > 0) &
(active_days['Game'] == 0)]['Social']
game_users = active_days[(active_days['Game'] > 0) &
(active_days['Social'] == 0)]['Game']
# Mann-Whitney U test
statistic, p_value = stats.mannwhitneyu(social_users, game_users,
alternative='greater')
return {
'social_mean': social_users.mean(),
'game_mean': game_users.mean(),
'p_value': p_value,
'n_social': len(social_users),
'n_game': len(game_users)
}
Common mistakes to avoid:
- Using row-level comparisons instead of user-level aggregations
- Assuming causation from correlation in observational data
- Relying solely on p-values without effect sizes
- Ignoring the difference between frequency (consistency) and duration (intensity)