PostgreSQL Summary Stats and Window Functions
Michel Semaan
Data Scientist
LAST_VALUE
LAST_VALUE(City) OVER (
ORDER BY Year ASC
RANGE BETWEEN
UNBOUNDED PRECEDING AND
UNBOUNDED FOLLOWING
) AS Last_City
RANGE BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING
LAST_VALUE
would return the row's value in the City columnROWS BETWEEN [START] AND [FINISH]
n PRECEDING
: n
rows before the current rowCURRENT ROW
: the current rown FOLLOWING
: n
rows after the current rowExamples
ROWS BETWEEN 3 PRECEDING AND CURRENT ROW
ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING
ROWS BETWEEN 5 PRECEDING AND 1 PRECEDING
Query
SELECT
Year, COUNT(*) AS Medals
FROM Summer_Medals
WHERE
Country = 'RUS'
AND Medal = 'Gold'
GROUP BY Year
ORDER BY Year ASC;
Result
| Year | Medals |
|------|--------|
| 1996 | 36 |
| 2000 | 66 |
| 2004 | 47 |
| 2008 | 43 |
| 2012 | 47 |
Query
WITH Russia_Medals AS (...)
SELECT
Year, Medals,
MAX(Medals)
OVER (ORDER BY Year ASC) AS Max_Medals
FROM Russia_Medals
ORDER BY Year ASC;
Result
| Year | Medals | Max_Medals |
|------|--------|------------|
| 1996 | 36 | 36 |
| 2000 | 66 | 66 |
| 2004 | 47 | 66 |
| 2008 | 43 | 66 |
| 2012 | 47 | 66 |
Query
WITH Russia_Medals AS (...)
SELECT
Year, Medals,
MAX(Medals)
OVER (ORDER BY Year ASC) AS Max_Medals,
MAX(Medals)
OVER (ORDER BY Year ASC
ROWS BETWEEN
1 PRECEDING AND CURRENT ROW)
AS Max_Medals_Last
FROM Russia_Medals
ORDER BY Year ASC;
Result
| Year | Medals | Max_Medals | Max_Medals_Last |
|------|--------|------------|-----------------|
| 1996 | 36 | 36 | 36 |
| 2000 | 66 | 66 | 66 |
| 2004 | 47 | 66 | 66 |
| 2008 | 43 | 66 | 47 |
| 2012 | 47 | 66 | 47 |
Query
WITH Russia_Medals AS (...)
SELECT
Year, Medals,
MAX(Medals)
OVER (ORDER BY Year ASC
ROWS BETWEEN
CURRENT ROW AND 1 FOLLOWING)
AS Max_Medals_Next
FROM Russia_Medals
ORDER BY Year ASC;
Result
| Year | Medals | Max_Medals_Next |
|------|--------|-----------------|
| 1996 | 36 | 66 |
| 2000 | 66 | 66 |
| 2004 | 47 | 47 |
| 2008 | 43 | 47 |
| 2012 | 47 | 47 |
PostgreSQL Summary Stats and Window Functions