Naming a window in SQL
Repeating the same OVER clause four times is how a typo gets in.
SELECT
month,
revenue,
SUM(revenue) OVER rolling AS rolling_sum,
AVG(revenue) OVER rolling AS rolling_avg,
MAX(revenue) OVER rolling AS rolling_peak
FROM monthly_revenue
WINDOW rolling AS (
ORDER BY month
ROWS BETWEEN 2 PRECEDING AND CURRENT ROW
)
ORDER BY month;
How it works
- The
WINDOWclause names a window definition once. - Every function then refers to it by name.
WINDOWsits afterHAVINGand before the finalORDER BY.
Keywords and builtins used here
ANDASAVGBETWEENBYCURRENTFROMMAXORDERROWROWSSELECTSUMmonth
The run, in numbers
- Lines
- 12
- Characters to type
- 263
- Tokens
- 52
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 33 seconds.
Step 6 of 9 in Window functions, step 12 of 24 in Analytics & reporting.