PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen
Michel Semaan
Data Scientist
Abfrage
SELECT
Country, Medal, COUNT(*) AS Awards
FROM summer_medals
WHERE
Year = 2008 AND Country IN ('CHN', 'RUS')
GROUP BY ROLLUP(Country, Medal)
ORDER BY Country ASC, Medal ASC;
null steht für eine GruppensummeErgebnis
| Country | Medal | Awards |
|---------|--------|--------|
| CHN | Bronze | 57 |
| CHN | Gold | 74 |
| CHN | Silver | 53 |
| CHN | null | 184 |
| RUS | Bronze | 56 |
| RUS | Gold | 43 |
| RUS | Silver | 44 |
| RUS | null | 143 |
| null | null | 327 |
COALESCE() nimmt Liste von Werten und gibt ersten Wert von links nach rechts zurück, der nicht null istCOALESCE(null, null, 1, null, 2) → 1null liefernROLLUP und CUBELAG und LEADAbfrage
SELECT
COALESCE(Country, 'Both countries') AS Country,
COALESCE(Medal, 'All medals') AS Medal,
COUNT(*) AS Awards
FROM summer_medals
WHERE
Year = 2008 AND Country IN ('CHN', 'RUS')
GROUP BY ROLLUP(Country, Medal)
ORDER BY Country ASC, Medal ASC;
Ergebnis
| Country | Medal | Awards |
|----------------|------------|--------|
| Both countries | All medals | 327 |
| CHN | All medals | 184 |
| CHN | Bronze | 57 |
| CHN | Gold | 74 |
| CHN | Silver | 53 |
| RUS | All medals | 143 |
| RUS | Bronze | 56 |
| RUS | Gold | 43 |
| RUS | Silver | 44 |
Vorher
| Country | Rank |
|---------|------|
| CHN | 1 |
| RUS | 2 |
| USA | 3 |
Rank ist überflüssig, weil Rangfolge schon klar istNachher
CHN, RUS, USA
STRING_AGG(column, separator) nimmt alle Werte einer Spalte und fügt sie zusammen, mit separator zwischen jedem Wert.STRING_AGG(Letter, ', ') verwandelt das hier...
| Letter |
|--------|
| A |
| B |
| C |
...in das
A, B, C
Vorher
WITH Country_Medals AS (
SELECT
Country, COUNT(*) AS Medals
FROM Summer_Medals
WHERE Year = 2012
AND Country IN ('CHN', 'RUS', 'USA')
AND Medal = 'Gold'
AND Sport = 'Gymnastics'
GROUP BY Country),
SELECT
Country,
RANK() OVER (ORDER BY Medals DESC) AS Rank
FROM Country_Medals
ORDER BY Rank ASC;
Nachher
WITH Country_Medals AS (...),
Country_Ranks AS (...)
SELECT STRING_AGG(Country, ', ')
FROM Country_Medals;
Ergebnis
CHN, RUS, USA
PostgreSQL: Zusammenfassende Statistiken und Fensterfunktionen