SQL Flow Field Guide

Compare window frames and rank tied results

Choose explicit window frames, distinguish peer-aware running totals from row-by-row totals, and return the top ranks without losing ties.

What you are trying to do

A finance analyst compares event amounts by team. Events can share a timestamp, and a dashboard must show the top two score ranks while preserving every tied row. Run this synthetic query in one SQL Server session.

Work through it

  1. The RANGE total orders only by EventAt, so rows with the same timestamp are peers and receive the same running total.
  2. The ROWS total adds a unique EventId tie-breaker. Its frame advances one physical row at a time in a repeatable order.
  3. LAG reads the prior amount in that repeatable event order. RANK assigns equal scores the same rank and leaves a gap after a tie.
  4. The outer filter keeps ranks one and two. Team 20 keeps both events tied at rank two.
  5. Change an amount, predict the peer group and rank, then compare the output. Read Microsoft's OVER frame and ranking references. Window frames · Ranking functions

Check your work

Both team 10 events at 09:00 show a RANGE total of 20. Their deterministic ROWS totals are 10 and 20. Team 20 returns all three events because the two amount-8 events share rank 2.

Practice SQL

Open in SQL Flow
;WITH EventRows AS (
    SELECT TeamId, EventAt, EventId, Amount
    FROM (VALUES
        (10, CONVERT(datetime2(0), '2026-10-01T09:00:00'), 1, CAST(10 AS decimal(10, 2))),
        (10, CONVERT(datetime2(0), '2026-10-01T09:00:00'), 2, CAST(10 AS decimal(10, 2))),
        (10, CONVERT(datetime2(0), '2026-10-01T10:00:00'), 3, CAST(5 AS decimal(10, 2))),
        (20, CONVERT(datetime2(0), '2026-10-01T09:00:00'), 4, CAST(12 AS decimal(10, 2))),
        (20, CONVERT(datetime2(0), '2026-10-01T10:00:00'), 5, CAST(8 AS decimal(10, 2))),
        (20, CONVERT(datetime2(0), '2026-10-01T10:00:00'), 6, CAST(8 AS decimal(10, 2)))
    ) AS v(TeamId, EventAt, EventId, Amount)
), Measured AS (
    SELECT TeamId, EventAt, EventId, Amount,
        SUM(Amount) OVER (PARTITION BY TeamId ORDER BY EventAt RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RangeTotal,
        SUM(Amount) OVER (PARTITION BY TeamId ORDER BY EventAt, EventId ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS RowTotal,
        LAG(Amount) OVER (PARTITION BY TeamId ORDER BY EventAt, EventId) AS PreviousAmount,
        RANK() OVER (PARTITION BY TeamId ORDER BY Amount DESC) AS ScoreRank
    FROM EventRows
)
SELECT TeamId, EventAt, EventId, Amount, RangeTotal, RowTotal, PreviousAmount, ScoreRank
FROM Measured
WHERE ScoreRank <= 2
ORDER BY TeamId, EventAt, EventId;

Knowledge check

Commands in this lesson

Next lesson Reconcile sets and label subtotal rows