Agregační okenní funkce

PostgreSQL Summary Stats and Window Functions

Michel Semaan

Data Scientist

Zdrojová tabulka

Dotaz

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

Výsledek

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

Agregační funkce

Dotaz MAX

WITH Brazil_Medals AS (...)

SELECT MAX(Medals) AS Max_Medals
FROM Brazil_Medals;

Výsledek MAX

18

Dotaz SUM

WITH Brazil_Medals AS (...)

SELECT SUM(Medals) AS Total_Medals
FROM Brazil_Medals;

Výsledek SUM

64
PostgreSQL Summary Stats and Window Functions

Okenní funkce MAX

Dotaz

WITH Brazil_Medals AS (...)

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

Výsledek

| 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

Okenní funkce SUM

Dotaz

WITH Brazil_Medals AS (...)

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

Výsledek

| 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

Rozdělení pomocí agregačních okenních funkcí

Dotaz

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

Výsledek

| 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        |

Dotaz

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

Výsledek

| 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

Pojďme cvičit!

PostgreSQL Summary Stats and Window Functions

Preparing Video For Download...