Ringkasan Statistik dan Window Functions di PostgreSQL
Michel Semaan
Data Scientist
Kueri
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 menandakan total grupHasil
| 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() mengambil daftar nilai dan mengembalikan nilai pertama yang bukan null, dari kiri ke kananCOALESCE(null, null, 1, null, 2) → 1nullROLLUP dan CUBELAG dan LEADKueri
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;
Hasil
| 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 |
Sebelum
| Country | Rank |
|---------|------|
| CHN | 1 |
| RUS | 2 |
| USA | 3 |
Rank berlebih karena peringkat tersiratSesudah
CHN, RUS, USA
STRING_AGG(column, separator) mengambil semua nilai kolom dan menggabungkannya, dengan separator di antara setiap nilaiSTRING_AGG(Letter, ', ') mengubah ini...
| Letter |
|--------|
| A |
| B |
| C |
...menjadi ini
A, B, C
Sebelum
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;
Sesudah
WITH Country_Medals AS (...),
Country_Ranks AS (...)
SELECT STRING_AGG(Country, ', ')
FROM Country_Medals;
Hasil
CHN, RUS, USA
Ringkasan Statistik dan Window Functions di PostgreSQL