KatInterview

Calculate Trailing 12-Month Segment Default Rates

SQL & DataModel answer
MediumModel answerSQL & Datasqlwindow-functionstime-series

Last 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 NameTypeDescription
monthDATEDate representing the record's month
segmentTEXTCustomer risk or product tier
defaultsINTCount of defaulted loans in that segment for the month
accountsINTTotal 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:

  1. 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]}$$
  2. 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.
  3. 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.
  4. If multiple entries exist for the same (segment, month) pair, ensure they are consolidated prior to computing rolling aggregates.
  5. 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.