
A running balance jumps from 10 to 60, even though the next transaction is only 20. The query can be correct SQL and still answer the wrong business question. In T-SQL, SUM with an ordered window and no explicit frame includes the current row’s peers: other rows with the same window sort values.
Decide what one step means. For a balance after each event, order events consistently and write a ROWS frame. For a total through an entire day, including every event that day, grouping peers can be exactly what you want. The following read-only fixture puts both answers next to each other.
WITH entries AS (
SELECT account_id, event_id, day_no, amount
FROM (VALUES
(1, 101, 1, 10),
(1, 102, 2, 20),
(1, 103, 2, 30),
(1, 104, 3, 5),
(2, 201, 1, 7)
) AS v(account_id, event_id, day_no, amount)
)
SELECT account_id, event_id, day_no, amount,
SUM(amount) OVER (
PARTITION BY account_id ORDER BY day_no
) AS through_day,
SUM(amount) OVER (
PARTITION BY account_id ORDER BY day_no, event_id
ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS through_event
FROM entries
ORDER BY account_id, day_no, event_id;Events 102 and 103 share day 2. Their through_day values are both 60; through_event advances from 30 to 60. Event 104 reaches 65 in both columns. Account 2 starts again at 7 because each account has its own partition. These are different definitions of progress, not different amounts of source data.
The event_id is a unique, non-null tie-breaker within each account in this fixture. Use a durable key with that property in real data, and agree on the intended event order. ROWS alone does not settle ties. An ORDER BY at the end of the query only arranges the displayed results; it cannot repair an ambiguous order inside OVER.
This example uses T-SQL window syntax supported by SQL Server 2012 and later. We ran it through KratosForge’s local T-SQL path at app commit c71bbf0, including a second run with the tied input rows reversed. Both returned the expected five rows. The associated regression tests check peer grouping and reject numeric RANGE offsets. These are local checks against documented rules; this article does not claim a live Fabric warehouse run or new Stable availability.
For a moving window, also name the unit carefully. ROWS BETWEEN 6 PRECEDING AND CURRENT ROW means at most seven records, not seven calendar days. Missing dates and multiple records per date change its meaning. T-SQL does not accept RANGE with a numeric PRECEDING or FOLLOWING offset; a calendar window needs a separate date-based design.
Add a tied sort value, a second partition and a reversed input order to the test for your next running total. Assert the intermediate balances as well as the final sum. A final total of 65 would pass for both definitions and leave the mistake undiscovered.
← All publications