Window frames in SQL
The frame decides which rows the window function can see from where it stands.
SELECT
day,
amount,
SUM(amount) OVER (
ORDER BY day
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
) AS three_row_sum,
SUM(amount) OVER (
ORDER BY day
RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW
) AS to_date,
SUM(amount) OVER (
ORDER BY day
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
) AS centered
FROM daily_revenue;
How it works
ROWScounts rows;RANGEcounts values of the sort key.- With ties,
RANGEpulls in every peer row —ROWSdoes not. - The default frame is the whole partition up to the current row's peers.
Keywords and builtins used here
ANDASBETWEENBYCURRENTFROMORDERROWROWSSELECTSUMday
The run, in numbers
- Lines
- 16
- Characters to type
- 315
- Tokens
- 67
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 42 seconds.
Step 5 of 9 in Window functions, step 11 of 24 in Analytics & reporting.