Funcții de fereastră agregate

Statistici sumare și funcții de fereastră în PostgreSQL

Michel Semaan

Data Scientist

Tabelul sursă

Interogare

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

Rezultat

| Year | Medals |
|------|--------|
| 1992 | 13     |
| 1996 | 5      |
| 2004 | 18     |
| 2008 | 14     |
| 2012 | 14     |
Statistici sumare și funcții de fereastră în PostgreSQL

Funcții agregate

Interogare MAX

WITH Brazil_Medals AS (...)

SELECT MAX(Medals) AS Max_Medals
FROM Brazil_Medals;

Rezultat MAX

18

Interogare SUM

WITH Brazil_Medals AS (...)

SELECT SUM(Medals) AS Total_Medals
FROM Brazil_Medals;

Rezultat SUM

64
Statistici sumare și funcții de fereastră în PostgreSQL

Funcția de fereastră MAX

Interogare

WITH Brazil_Medals AS (...)

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

Rezultat

| Year | Medals | Max_Medals |
|------|--------|------------|
| 1992 | 13     | 13         |
| 1996 | 5      | 13         |
| 2004 | 18     | 18         |
| 2008 | 14     | 18         |
| 2012 | 14     | 18         |
Statistici sumare și funcții de fereastră în PostgreSQL

Funcția de fereastră SUM

Interogare

WITH Brazil_Medals AS (...)

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

Rezultat

| Year | Medals | Medals_RT |
|------|--------|-----------|
| 1992 | 13     | 13        |
| 1996 | 5      | 18        |
| 2004 | 18     | 36        |
| 2008 | 14     | 50        |
| 2012 | 14     | 64        |
Statistici sumare și funcții de fereastră în PostgreSQL

Partiționare cu funcții de fereastră agregate

Interogare

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

Rezultat

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

Interogare

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

Rezultat

| 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        |
Statistici sumare și funcții de fereastră în PostgreSQL

Să exersăm!

Statistici sumare și funcții de fereastră în PostgreSQL

Preparing Video For Download...