Aggregate Window Functions and Frames
Aggregate Window Functions and Frames
functions
P O S TG R E S Q L S U M M A R Y S TAT S A N D W I N D O W F U N C T I O N S
Michel Semaan
Data Scientist
Source table
Query Result
what if you want to see the max meddals earned so far, or calculate cumulative sum of medals earned?
Result Result
Michel Semaan
Data Scientist
Motivation
LAST_VALUE
LAST_VALUE(City) OVER (
ORDER BY Year ASC
RANGE BETWEEN
UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING
) AS Last_City
Without the frame, LAST_VALUE would return the row's value in the City column
By default, a frame starts at the beginning of a table or partition and ends at the current row
Examples
Michel Semaan
Moving averages
Overview
Moving average (MA): Average of last n periods
Example: 10-day MA of units sold in sales is the average of the last 10 days' sold units
Used to indicate momentum/trends if a days's units sold is higher than its moving average, then the next day more units are
likely to be sold
Used to indicate performance; if the sum is going down, overall performance is going down
Table range_rt col treats the rwos with duplicate values as single rows, summing them up first then displaying that sum for each duplicate row