Rank and compare rows without collapsing them
Use window functions to add per-team rank, running totals, and previous-row comparisons while preserving each input row.
What you are trying to do
A product team reviews weekly effort. The report needs a stable row number, a running total within each team, and the previous week's effort.
Work through it
- Read PARTITION BY as the boundary that restarts each calculation for a team.
- Follow the ordering keys and the explicit ROWS frame for the running total.
- Compare LAG with the previous row in the same team ordering.
- Check that the three input rows remain three output rows.
Check your work
The three output rows are North week 1 with position 1, running effort 5, and no prior effort; North week 2 with position 2, running effort 12, and prior effort 5; and South week 1 with position 1, running effort 4, and no prior effort.
Practice SQL
Open in SQL FlowSELECT Team, WeekNumber, Effort,
ROW_NUMBER() OVER (PARTITION BY Team ORDER BY WeekNumber) AS Position,
SUM(Effort) OVER (PARTITION BY Team ORDER BY WeekNumber ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RunningEffort,
LAG(Effort) OVER (PARTITION BY Team ORDER BY WeekNumber) AS PriorEffort
FROM (VALUES (N'North', 1, 5), (N'North', 2, 7), (N'South', 1, 4)) AS WeeklyWork(Team, WeekNumber, Effort)
ORDER BY Team, WeekNumber;
Knowledge check
Commands in this lesson
Next lesson Walk a dependency tree with a recursive CTE