Window Functions
Window functions compute values across a sliding window or partition of rows, without collapsing the table. All window functions are written under the with statement.
rank — ranking
Rank rows by a column value.
Basic rank
Ascending rank
Percentile rank
Returns a value between 0 and 1:
Partitioned rank (rank within groups)
Use by to rank within groups:
lag / lead — shifted values
Access values from a previous (lag) or future (lead) row.
Basic lag
The order clause specifies which column defines row order. It is required.
Lead
With partition
Larger offsets
Cumulative statistics
Compute running totals, averages, min, and max.
| Statement | Description |
|---|---|
cumsum <col> as <name> |
Running sum |
cummean <col> as <name> |
Running average |
cummin <col> as <name> |
Running minimum |
cummax <col> as <name> |
Running maximum |
The order clause specifies row order and is required. Use by for partitioned cumulation.
with sales
cumsum amount as running_total
order date
with sales
cummean amount as running_avg
order date
with sales
cummin amount as running_min
by region
order date
with sales
cummax amount as running_max
by region
order date
Partitioned cumulation
rolling — rolling window statistics
Compute statistics over a sliding window of N rows.
Rolling functions
| Function | Description |
|---|---|
rolling mean <col> <n> |
Rolling average |
rolling sum <col> <n> |
Rolling sum |
rolling std <col> <n> |
Rolling standard deviation |
rolling min <col> <n> |
Rolling minimum |
rolling max <col> <n> |
Rolling maximum |
Options
with sales
rolling mean amount 4 as rolling_avg
by region # compute within groups
order date # required: defines row order