Window Functions
About
Window functions allow you to run aggregate functions without grouping the data.
Specifying PARTITION BY works like creating aggregations like GROUP BY.
Window functions are powerful as it lets you aggregate data in different ways in the same query.
Windowing Functions
Window function summary:
frame
computation
generic aggs.
e.g. SUM, AVG
row access
FIRST_VALUE
first frame value
row access
LAST_VALUE
last frame value
row access
NTH_VALUE
nth frame value
partition
row access
LAG
row before current
row access
LEAD
row after current
row access
ROW_NUMBER
current row number
ranking
CUME_DIST
cumulative distribution
ranking
DENSE_RANK
rank without gaps
ranking
NTILE
rank in n partitions
ranking
PERCENT_RANK
percent rank
ranking
RANK
rank with gaps
Window function never process rows outside their partitions. However, without PARTITION BY the partition is the entire set.
over
partition by
partition by with order by
lead & lag
Useful functions to compare data of CURRENT ROW with any other row in its PARTITION group. (LEAD going forward, and LAG going backwards)
first_value & last_value
Get the first, last or nth row value in a PARTITION group.
Dynamic Windows
You can create sliding dynamic windows for the data by specifying window frames.
window frames
Window frames are used to indicate how many rows around the current view, the window function should include.
RANGE can only be used with UNBOUNDED values.
There is also a slight difference in how aggregations are treated in RANGE when compared to ROWS.
If no range is specified, a window frame by default uses:
UNBOUNDED means, consider all the rows before (PRECEDING) / after (FOLLOWING) the current one.
Examples
Last updated