Forward Cumulative Loss Across Policy Renewal Terms
Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen
Problem Statement
An insurance carrier tracks incurred claim costs across successive renewal periods in a table named policy_term_losses. Each record represents one renewal period (term_id) belonging to a parent contract (policy_id), sequenced chronologically by the integer term_sequence (where larger integers denote later renewal periods).
For every record in policy_term_losses, compute its forward cumulative loss (ultimate_loss): the total of loss_amount on that record plus loss_amount across every subsequent renewal period under the same policy_id (i.e., all rows sharing policy_id whose term_sequence is greater than or equal to the current row's term_sequence).
Emit one output row per input row (in any row order) with five columns:
policy_idterm_idterm_sequenceloss_amountultimate_loss(rounded to 2 decimal places)
Input Schema
Table policy_term_losses:
| Column | Type | Description |
|---|---|---|
policy_id |
VARCHAR |
Contract identifier |
term_id |
VARCHAR |
Renewal period identifier (maps to a single policy_id) |
term_sequence |
INTEGER |
Chronological index within policy_id (higher values are later) |
term_start_date |
DATE |
Effective start date of the period |
term_end_date |
DATE |
Expiration date of the period |
loss_amount |
DECIMAL(18,2) |
Net incurred loss recorded for this period |
Examples
Example 1
Input (policy_term_losses):
| policy_id | term_id | term_sequence | term_start_date | term_end_date | loss_amount |
|---|---|---|---|---|---|
| POL-10 | TRM-1 | 1 | 2021-06-01 | 2022-05-31 | 240.00 |
| POL-10 | TRM-2 | 2 | 2022-06-01 | 2023-05-31 | 85.50 |
| POL-10 | TRM-3 | 3 | 2023-06-01 | 2024-05-31 | 34.50 |
| POL-20 | TRM-9 | 1 | 2023-01-15 | 2024-01-14 | 120.00 |
Expected output:
| policy_id | term_id | term_sequence | loss_amount | ultimate_loss |
|---|---|---|---|---|
| POL-10 | TRM-1 | 1 | 240.00 | 360.00 |
| POL-10 | TRM-2 | 2 | 85.50 | 120.00 |
| POL-10 | TRM-3 | 3 | 34.50 | 34.50 |
| POL-20 | TRM-9 | 1 | 120.00 | 120.00 |
Walk-through: Within POL-10, sequence 1 sums sequences 1, 2, 3 (240.00 + 85.50 + 34.50 = 360.00), sequence 2 sums sequences 2, 3 (85.50 + 34.50 = 120.00), and sequence 3 keeps its own 34.50. POL-20 is partitioned independently and has a single period (120.00).
Example 2
Input (policy_term_losses):
| policy_id | term_id | term_sequence | term_start_date | term_end_date | loss_amount |
|---|---|---|---|---|---|
| POL-55 | RN-1 | 1 | 2020-04-01 | 2021-03-31 | 500.00 |
| POL-55 | RN-2 | 2 | 2021-04-01 | 2022-03-31 | -120.00 |
| POL-55 | RN-3 | 3 | 2022-04-01 | 2023-03-31 | 0.00 |
| POL-55 | RN-4 | 4 | 2023-04-01 | 2024-03-31 | 45.00 |
Expected output:
| policy_id | term_id | term_sequence | loss_amount | ultimate_loss |
|---|---|---|---|---|
| POL-55 | RN-1 | 1 | 500.00 | 425.00 |
| POL-55 | RN-2 | 2 | -120.00 | -75.00 |
| POL-55 | RN-3 | 3 | 0.00 | 45.00 |
| POL-55 | RN-4 | 4 | 45.00 | 45.00 |
Walk-through: Downward reserve revisions (-120.00) and zero-loss periods (0.00) combine algebraically with later periods: sequence 2 evaluates to -120.00 + 0.00 + 45.00 = -75.00, and sequence 1 evaluates to 500.00 + (-75.00) = 425.00.
Constraints
- Every
(policy_id, term_sequence)combination appears at most once, and eachterm_idbelongs to a singlepolicy_id. - Sequence order depends solely on
term_sequence(never onterm_idtext order orterm_start_date/term_end_date, which may even beNULL). loss_amountmay be positive, zero, or negative (orNULL, which contributes nothing to a sum).- Return rows in any order.
Step-by-step walkthrough
Understand what ultimate loss means per term
We are given
policy_term_losses(policy_id, term_id, term_sequence, term_start_date, term_end_date, loss_amount), with one row per policy term. Within eachpolicy_id, the integerterm_sequencegives chronological order (larger numbers mean later renewal terms), and(policy_id, term_sequence)has at most one row.We must return every input row (no collapsing) with a fifth column
ultimate_loss: the sum ofloss_amountfrom the current term through the final term of that same policy:Policy POL-10 ordered by term_sequence: TRM-1 (seq 1): loss = 240.00 ---> [240.00 + 85.50 + 34.50] = 360.00 TRM-2 (seq 2): loss = 85.50 ---> [85.50 + 34.50] = 120.00 TRM-3 (seq 3): loss = 34.50 ---> [34.50] = 34.50Notice that
term_start_dateandterm_end_dateare not needed at all — even if a date isNULL,term_sequencealone defines which terms come at or after the current term.Start with the brute-force mental model
We can translate the definition word for word into SQL using a correlated subquery — an inner
SELECTthat looks up matching future rowsffor each outer rowt:SELECT t.policy_id, t.term_id, t.term_sequence, t.loss_amount, ROUND( (SELECT SUM(f.loss_amount) FROM policy_term_losses AS f WHERE f.policy_id = t.policy_id AND f.term_sequence >= t.term_sequence), 2 ) AS ultimate_loss FROM policy_term_losses AS tThis produces the right answer, but for a policy with
kterms it re-scans up tokrows for each of thosekterms (O(k^2)work per policy). Because we are simply computing a reverse running total (a suffix sum) within each policy, a window function can compute every term's answer in one pass over sorted rows.Build the forward-looking window frame
A window function computes an aggregate across related rows without merging them into a single row. Inside
SUM(loss_amount) OVER (...), three clauses control which rows get summed:PARTITION BY policy_id: splits the table into separate per-policy buckets so losses fromPOL-10never leak intoPOL-20.ORDER BY term_sequence: lines up a policy's terms from earliest to latest (1, 2, 3, ...).RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING: sets the window frame — the slice of the partition summed for the current row — to start at the currentterm_sequencevalue and extend all the way to the last row of that policy.
Why must we write out the frame explicitly? Whenever
ORDER BYappears insideOVER (...)with no frame clause, SQL defaults toRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW— summing from the first term up to the current term (240.0, 325.5, 360.0, or "loss to date"), which is the exact opposite direction!Default frame (UNBOUNDED PRECEDING .. CURRENT ROW): [TRM-1] -> [TRM-1..TRM-2] -> [TRM-1..TRM-3] (240.0, 325.5, 360.0) Forward frame (CURRENT ROW .. UNBOUNDED FOLLOWING): [TRM-1..TRM-3] -> [TRM-2..TRM-3] -> [TRM-3] (360.0, 120.0, 34.5)Because
(policy_id, term_sequence)is unique,ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING(or flipping the sort toORDER BY term_sequence DESCwithROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) gives the exact same values. UsingRANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWINGreads closest to the mathematical ruleterm_sequence >= current term_sequence, and would even include tied sequence numbers together if duplicates ever occurred.Round away SQLite floating-point noise
In PostgreSQL or Snowflake,
DECIMAL(18, 2)arithmetic is exact in base 10. SQLite, however, stores decimal fractions as binary floating-point numbers, where10.10 + 20.20 + 0.30evaluates to30.599999999999998. Wrapping the window sum inROUND(..., 2)keeps everyultimate_lossclean to 2 decimal places while leavingloss_amountuntouched:ROUND( SUM(loss_amount) OVER ( -- Keep each policy isolated so losses never cross policy boundaries. PARTITION BY policy_id -- Order terms chronologically and sum from current row to final term. ORDER BY term_sequence RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING ), -- Round to 2 decimals so SQLite binary floats stay exact to the cent. 2 ) AS ultimate_lossTrace Example 1 and Example 2 (including negative adjustments)
Let's trace both Example 1 (
POL-10andPOL-20) and Example 2 (POL-55, which has a downward-120.00reserve revision and a0.00term):policy_id term_id seq loss_amount terms summed in frame ultimate_loss --------- ------- --- ----------- ------------------------------- ------------- POL-10 TRM-1 1 240.00 240.00 + 85.50 + 34.50 360.00 POL-10 TRM-2 2 85.50 85.50 + 34.50 120.00 POL-10 TRM-3 3 34.50 34.50 34.50 POL-20 TRM-9 1 120.00 120.00 120.00 POL-55 RN-1 1 500.00 500.00 + (-120.00) + 0.00 + 45.00 425.00 POL-55 RN-2 2 -120.00 (-120.00) + 0.00 + 45.00 -75.00 POL-55 RN-3 3 0.00 0.00 + 45.00 45.00 POL-55 RN-4 4 45.00 45.00 45.00Negative and zero losses need no special
CASEhandling — ordinary addition handles downward adjustments naturally, even whenultimate_lossdrops below zero.Complete SQL query
SELECT policy_id, term_id, term_sequence, loss_amount, -- Sum this term and every later term (term_sequence >= current) within the -- same policy while keeping one output row per policy term. ROUND( SUM(loss_amount) OVER ( -- Keep each policy isolated so losses never cross policy boundaries. PARTITION BY policy_id -- Order terms chronologically and sum from current row to final term. ORDER BY term_sequence RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING ), -- Round to 2 decimals so SQLite binary floats stay exact to the cent. 2 ) AS ultimate_loss FROM policy_term_losses✅ Submit now — all tests should pass.
Intuition & how it works
Imagine opening a folder for a single insurance policy that holds one page per renewal term (Term 1, Term 2, Term 3). A normal running total adds from the first page downward to answer "what is our loss to date?" Here we want the mirror image — starting on any term's page, what is the sum of this term's loss plus every future term's loss through the end of the policy, written right onto each page without removing any pages from the folder.
Naive approaches either lose rows or repeat work unnecessarily. Using GROUP BY policy_id collapses an entire policy down to a single summary row instead of keeping one row per term, while a correlated subquery (an inner SELECT that re-executes for every outer row) re-scans a policy's k terms for each of its k rows in O(k^2) time. Even with a window function (a SQL OVER (...) calculation that attaches a group or sequence summary to each row without collapsing rows), writing SUM(loss_amount) OVER (PARTITION BY policy_id ORDER BY term_sequence) without specifying a window frame (the exact range of rows inside the partition included in each row's calculation) defaults to summing from the first term up to the current row — computing loss-to-date instead of remaining ultimate loss.
Tracing POL-10 from Example 1 ((TRM-1, seq 1, 240.00), (TRM-2, seq 2, 85.50), (TRM-3, seq 3, 34.50)), PARTITION BY policy_id isolates POL-10 from POL-20, and ORDER BY term_sequence lines its losses up as [240.00, 85.50, 34.50]. The explicit frame RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING tells the engine to sum from the current row to the end of POL-10's partition: 240.00 + 85.50 + 34.50 = 360.0 at TRM-1, 85.50 + 34.50 = 120.0 at TRM-2, and 34.5 at TRM-3.
Complexity
- Time — O(N log N) without an index, or O(N) with a composite index: Let
Nbe the total number of rows across all policies. Without an index, the database sorts allNrows by(policy_id, term_sequence)inO(N log N)time and then sweeps through each partition (each isolated per-policy group of rows) inO(N)time to maintain the sliding window sum (compared toO(k^2)perk-term policy for a self-join or correlated subquery). With a composite B-tree index onpolicy_term_losses(policy_id, term_sequence), the engine reads rows already sorted in window order, skipping theO(N log N)sort completely; addingterm_id, loss_amountcreates a covering index (an index holding every column the query touches) so the main table never needs to be read. - Space — O(N): Sorting and buffering partitions for window evaluation takes
O(N)memory across theNoutput rows (orO(k)per policy ofkterms when reading in index order).
Edge cases
- Single-term policies: The forward frame contains only that single row, so
ultimate_lossequalsloss_amount. - Negative adjustments and zero-loss terms: Downward reserve adjustments (
loss_amount < 0) and0losses add normally, meaning an earlier term'sultimate_losscan be smaller than its ownloss_amountor even negative (-120.00 + 0.00 + 45.00 = -75.00in Example 2). - Gaps in
term_sequenceor string-sorting traps interm_id: Sequence gaps like2, 9, 10or string IDs where'T10' < 'T2'alphabetically do not affect the result because ordering uses the integerterm_sequence. - Missing (
NULL) dates:term_start_dateandterm_end_dateare never referenced, soNULLdates on newly created renewal terms do not change the order. - Binary floating-point cents in SQLite: SQLite stores
DECIMALvalues using binary floating-point numbers (base-2 approximations where10.10 + 20.20 + 0.30yields30.599999999999998), whichROUND(..., 2)cleans up. - NULL
loss_amount: SQL'sSUMignoresNULLvalues and sums the remaining non-NULLterms in the frame (returningNULLonly if every term from the current row onward hasNULLloss_amount). - Empty table: Returns zero rows with the five required column names.
Common mistakes
- Omitting
RANGE BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING: WithORDER BY term_sequencealone, SQL defaults toRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW, returning forward cumulative loss-to-date (240.0, 325.5, 360.0) instead of ultimate loss (360.0, 120.0, 34.5). - Forgetting
PARTITION BY policy_id: Without partitioning, one policy's losses continue summing into every policy that sorts after it. - Ordering by
term_idorterm_start_date: Alphabetical ordering puts'T10'before'T2', andNULLdates sort first in SQLite, scrambling the chronological term order. - Using
GROUP BY policy_id: Grouping collapses each policy to one row instead of preserving one row per policy term. - Filtering
term_sequencein the sameWHEREclause:WHEREruns before window functions, soWHERE term_sequence = 1strips out later terms beforeSUM(...) OVER (...)can include them; always filter specific terms in an outer query around a CTE.
Follow-up questions
- How would you return cumulative loss-to-date and each term's fraction of total policy loss alongside ultimate loss? Combine three window frames over
PARTITION BY policy_idin oneSELECT: the defaultORDER BY term_sequenceframe forloss_to_date, ourCURRENT ROW AND UNBOUNDED FOLLOWINGframe forultimate_loss, and an unorderedOVER (PARTITION BY policy_id)window for total policy loss (guarding division withNULLIF(..., 0)since negative adjustments can make a policy's net total0):
sql
SELECT
policy_id,
term_id,
term_sequence,
ROUND(SUM(loss_amount) OVER (PARTITION BY policy_id ORDER BY term_sequence), 2) AS loss_to_date,
ROUND(
1.0 * loss_amount
/ NULLIF(SUM(loss_amount) OVER (PARTITION BY policy_id), 0),
4
) AS share_of_policy_loss
FROM policy_term_losses
- How could you express the same forward sum in SQL dialects that lack window functions? Self-join each policy term
tto every termfof the same policy withf.term_sequence >= t.term_sequence, thenGROUP BYt's columns and sumf.loss_amount. This produces identical results (because(policy_id, term_sequence)is unique) at the cost ofO(k^2)work perk-term policy:
sql
SELECT
t.policy_id,
t.term_id,
t.term_sequence,
t.loss_amount,
ROUND(SUM(f.loss_amount), 2) AS ultimate_loss
FROM policy_term_losses AS t
JOIN policy_term_losses AS f
ON f.policy_id = t.policy_id
AND f.term_sequence >= t.term_sequence
GROUP BY t.policy_id, t.term_id, t.term_sequence, t.loss_amount
- How would you compute this column on a pandas DataFrame in Python? Sort each policy in descending
term_sequenceorder (last term -> first term), then run a grouped cumulative sum (groupby("policy_id")["loss_amount"].cumsum()) and round to 2 decimal places — reversing the sort order turns a forward suffix sum into pandas' standard top-downcumsum():
python
df = df.sort_values(["policy_id", "term_sequence"], ascending=[True, False])
df["ultimate_loss"] = df.groupby("policy_id")["loss_amount"].cumsum().round(2)
Follow-up questions
- How would you return cumulative loss-to-date and each term's fraction of total policy loss alongside ultimate loss?
- How could you express the same forward sum in SQL dialects that lack window functions?
- How would you compute this column on a pandas DataFrame in Python?
Similar questions
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months
- Build Rolling User Features for Experiment Regression
- Week-over-Week Net Order Revenue Change