Calculate Trailing 12-Month Segment Default Rates
SQL & DataModel answerLast updated
Write SQL to aggregate defaults and accounts over a trailing 12-month window for each customer segment, correctly handling non-consecutive dates and zero division.
You are analyzing credit portfolio metrics for a financial institution. You are given a table named loans with the following schema:
| Column Name | Type | Description |
|---|---|---|
month | DATE | Date representing the record's month |
segment | TEXT | Customer risk or product tier |
defaults | INT | Count of defaulted loans in that segment for the month |
accounts | INT | Total active accounts in that segment for the month |
Write a SQL query that calculates the trailing 12-month default rate for each customer segment and month.
Requirements:
- For any given segment and target month $M$, the trailing 12-month default rate is defined as: $$\text{Rolling Default Rate} = \frac{\sum \text{defaults over months } [M-11, M]}{\sum \text{accounts over months } [M-11, M]}$$
- Do not average the monthly default rates. You must sum the total defaults over the 12-month frame and divide by the total active accounts over the same frame.
- Handle missing temporal entries gracefully: a 12-month window must reflect a true 12-calendar-month period rather than merely the last 12 existing rows.
- If multiple entries exist for the same
(segment, month)pair, ensure they are consolidated prior to computing rolling aggregates. - Prevent division-by-zero errors when total accounts in a trailing period equal zero.
Hints
Hint 1
Be careful using `ROWS BETWEEN 11 PRECEDING AND CURRENT ROW` directly on source data—if a segment has missing months, `ROWS` will reach further back in time than 12 calendar months.
Hint 2
Consider using `RANGE BETWEEN INTERVAL '11 months' PRECEDING AND CURRENT ROW` or building a continuous monthly date calendar (densification) before applying `ROWS`.
Hint 3
Ensure you sum defaults and accounts separately in window functions before dividing, and use `NULLIF` or explicit type casting to handle zero denominators and avoid integer division.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach & Architectural Considerations
When generating rolling metrics across time series partitions, three common pitfalls frequently lead to subtle reporting bugs:
- Sum of Ratios vs. Ratio of Sums: Calculating $\text{AVG}(\text{defaults} / \text{accounts})$ calculates an unweighted average of monthly ratios. A month with 10 accounts carries the same weight as a month with 1,000,000 accounts. The standard financial/risk metric requires pooling total defaults and total exposure over the trailing window first, then evaluating the fraction.
- Temporal Gaps (
ROWSvs.RANGE): Using standardROWS BETWEEN 11 PRECEDING AND CURRENT ROWassumes that data points occur continuously at fixed monthly steps. If a segment skips a month due to inactivity or data loss, a 12-row window will span 13 or more calendar months. - Integer Truncation & Division by Zero: In dialects like PostgreSQL or SQL Server, dividing two
INTfields results in integer truncation (1 / 2 = 0). Additionally, ifaccountstotals0over a window, the query must returnNULLrather than failing.
Method 1: Using RANGE Frame Specification (Recommended / Modern SQL)
If your database engine supports interval arithmetic within RANGE frames (e.g., PostgreSQL 11+, DuckDB, Snowflake), you can evaluate frame bounds relative to the actual DATE value rather than row offset counts.
WITH pre_aggregated AS (
-- Group duplicates and truncate all dates to month start
SELECT
segment,
DATE_TRUNC('month', month)::DATE AS month_start,
SUM(defaults) AS defaults,
SUM(accounts) AS accounts
FROM loans
GROUP BY 1, 2
)
SELECT
segment,
month_start AS month,
defaults,
accounts,
SUM(defaults) OVER w AS defaults_12m,
SUM(accounts) OVER w AS accounts_12m,
ROUND(
SUM(defaults) OVER w :: NUMERIC / NULLIF(SUM(accounts) OVER w, 0),
4
) AS rolling_default_rate
FROM pre_aggregated
WINDOW w AS (
PARTITION BY segment
ORDER BY month_start
RANGE BETWEEN INTERVAL '11 months' PRECEDING AND CURRENT ROW
)
ORDER BY segment, month_start;
Method 2: Calendar Densification (Universal Compatibility)
For SQL engines that do not support dynamic INTERVAL logic in RANGE frames (or when strict physical row alignment is required), we build a dense date spine per segment using generate_series.
WITH aggregated AS (
-- Step 1: Consolidate records to single row per (segment, month)
SELECT
segment,
DATE_TRUNC('month', month)::DATE AS month_start,
SUM(defaults) AS defaults,
SUM(accounts) AS accounts
FROM loans
GROUP BY 1, 2
),
segment_bounds AS (
-- Step 2: Determine date scope for each segment
SELECT
segment,
MIN(month_start) AS min_m,
MAX(month_start) AS max_m
FROM aggregated
GROUP BY segment
),
calendar_spine AS (
-- Step 3: Generate a continuous monthly grid per segment
SELECT
sb.segment,
gs::DATE AS month_start
FROM segment_bounds sb
CROSS JOIN LATERAL generate_series(sb.min_m, sb.max_m, INTERVAL '1 month') AS gs
),
dense_dataset AS (
-- Step 4: Left join data onto calendar grid, filling missing months with 0
SELECT
c.segment,
c.month_start,
COALESCE(a.defaults, 0) AS defaults,
COALESCE(a.accounts, 0) AS accounts,
(a.month_start IS NOT NULL) AS observed_month
FROM calendar_spine c
LEFT JOIN aggregated a
ON c.segment = a.segment
AND c.month_start = a.month_start
),
rolling_sums AS (
-- Step 5: Execute fixed 12-row window sum safely
SELECT
segment,
month_start,
observed_month,
SUM(defaults) OVER w AS rolling_defaults,
SUM(accounts) OVER w AS rolling_accounts
FROM dense_dataset
WINDOW w AS (
PARTITION BY segment
ORDER BY month_start
ROWS BETWEEN 11 PRECEDING AND CURRENT ROW
)
)
SELECT
segment,
month_start AS month,
rolling_defaults,
rolling_accounts,
ROUND(
rolling_defaults::NUMERIC / NULLIF(rolling_accounts, 0),
4
) AS rolling_default_rate
FROM rolling_sums
WHERE observed_month = TRUE -- Return only actual reported baseline months
ORDER BY segment, month_start;
Complexity Analysis
- Time Complexity:
- Aggregation: $\mathcal{O}(N)$ where $N$ is the raw row count.
- Sorting & Window Operations: $\mathcal{O}(M \log M)$ per segment, where $M$ is the number of distinct monthly periods. Aggregate time across all segments is $\mathcal{O}(M \log M)$.
- Space Complexity: $\mathcal{O}(M)$ auxiliary space needed to build intermediate temporal structures/spines.
Edge Cases Handled
- Partial Windows (Start of Time Series): The first 1 to 11 months for a segment naturally evaluate over whatever trailing months are present. If strict 12-month completeness is mandatory, a count check
COUNT(*) OVER w = 12can be added to filter partial windows. - Zero Accounts (
accounts = 0):NULLIF(accounts_12m, 0)converts zero toNULL, causing standard division to outputNULLinstead of throwing a run-time exception. - Data Gaps: Handled seamlessly via
RANGEframe evaluation or explicit grid filling via CTEs.