Aggregate window functions

PostgreSQL Summary Stats and Window Functions

Michel Semaan

Data Scientist

Source table

Query

SELECT
  Year, COUNT(*) AS Medals
FROM Summer_Medals
WHERE
  Country = 'BRA'
  AND Medal = 'Gold'
  AND Year >= 1992
GROUP BY Year
ORDER BY Year ASC;

Result

| Year | Medals |
|------|--------|
| 1992 | 13     |
| 1996 | 5      |
| 2004 | 18     |
| 2008 | 14     |
| 2012 | 14     |
PostgreSQL Summary Stats and Window Functions

Aggregate functions

MAX Query

WITH Brazil_Medals AS (...)

SELECT MAX(Medals) AS Max_Medals
FROM Brazil_Medals;

MAX Result

18

SUM Query

WITH Brazil_Medals AS (...)

SELECT SUM(Medals) AS Total_Medals
FROM Brazil_Medals;

SUM Result

64
PostgreSQL Summary Stats and Window Functions

MAX Window function

Query

WITH Brazil_Medals AS (...)

SELECT
  Year, Medals,
  MAX(Medals)
    OVER (ORDER BY Year ASC) AS Max_Medals
FROM Brazil_Medals;

Result

| Year | Medals | Max_Medals |
|------|--------|------------|
| 1992 | 13     | 13         |
| 1996 | 5      | 13         |
| 2004 | 18     | 18         |
| 2008 | 14     | 18         |
| 2012 | 14     | 18         |
PostgreSQL Summary Stats and Window Functions

SUM Window function

Query

WITH Brazil_Medals AS (...)

SELECT
  Year, Medals,
  SUM(Medals) OVER (ORDER BY Year ASC) AS Medals_RT
FROM Brazil_Medals;

Result

| Year | Medals | Medals_RT |
|------|--------|-----------|
| 1992 | 13     | 13        |
| 1996 | 5      | 18        |
| 2004 | 18     | 36        |
| 2008 | 14     | 50        |
| 2012 | 14     | 64        |
PostgreSQL Summary Stats and Window Functions

Partitioning with aggregate window functions

Query

WITH Medals AS (...)
SELECT Year, Country, Medals,
  SUM(Medals) OVER (...)
FROM Medals;

Result

| Year | Country | Medals | Medals_RT | 
|------|---------|--------|-----------|
| 2004 | BRA     | 18     | 18        |
| 2008 | BRA     | 14     | 32        |
| 2012 | BRA     | 14     | 46        |
| 2004 | CUB     | 31     | 77        |
| 2008 | CUB     | 2      | 79        |
| 2012 | CUB     | 5      | 84        |

Query

WITH Medals AS (...)
SELECT Year, Country, Medals,
  SUM(Medals) OVER (PARTITION BY Country ...)
FROM Medals;

Result

| Year | Country | Medals | Medals_RT | 
|------|---------|--------|-----------|
| 2004 | BRA     | 18     | 18        |
| 2008 | BRA     | 14     | 32        |
| 2012 | BRA     | 14     | 46        |
| 2004 | CUB     | 31     | 31        |
| 2008 | CUB     | 2      | 33        |
| 2012 | CUB     | 5      | 38        |
PostgreSQL Summary Stats and Window Functions

Let's practice!

PostgreSQL Summary Stats and Window Functions

Preparing Video For Download...