ROLLUP

以資料驅動的 SQL 決策制定

Bart Baesens

Professor Data Science and Analytics

資料表 renting_extended

資料表 renting_extended 的前幾列:

| renting_id | country  | genre  | rating |
|------------|----------|--------|--------|
| 2          | Belgium  | Drama  | 10     |
| 32         | Belgium  | Drama  | 10     |
| 203        | Austria  | Drama  | 6      |
| 292        | Austria  | Comedy | 8      |
| 363        | Belgium  | Drama  | 7      |
| .......... | ........ | ...... | ...... |
以資料驅動的 SQL 決策制定

使用 ROLLUP 的查詢

SELECT country, 
       genre, 
       COUNT(*)
FROM renting_extended
GROUP BY ROLLUP (country, genre);
  • 聚合層級
    • 各 country 與 genre 組合的彙總
    • 只以 country 的彙總
    • 全體總彙總
以資料驅動的 SQL 決策制定

使用 ROLLUP 的查詢

SELECT country, 
       genre, 
       COUNT(*)
FROM renting_extended
GROUP BY ROLLUP (country, genre);
| country | genre  | count |
|---------|--------|-------|
| null    | null   | 22    |
| Austria | Comedy | 2     |
| Belgium | Drama  | 15    |
| Austria | Drama  | 4     |
| Belgium | Comedy | 1     |
| Belgium | null   | 16    |
| Austria | null   | 6     |
以資料驅動的 SQL 決策制定

ROLLUP 中的順序

SELECT country, 
       genre, 
       COUNT(*)
FROM renting_extended
GROUP BY ROLLUP (genre, country);
| country | genre  | count |
|---------|--------|-------|
| null    | null   | 22    |
| Austria | Comedy | 2     |
| Belgium | Drama  | 15    |
| Austria | Drama  | 4     |
| Belgium | Comedy | 1     |
| null    | Comedy | 3     |
| null    | Drama  | 19    |
以資料驅動的 SQL 決策制定

ROLLUP 重點整理

  • 回傳值的階層彙總,例如 ROLLUP (country, genre)
    • 各國家與各類型的電影租借數
    • 各國家的電影租借數
    • 電影租借總數
  • 每一步會移除一層細節
  • 在 ROLLUP 中,欄位順序很重要
以資料驅動的 SQL 決策制定

租借與評分的筆數

SELECT country, 
       genre, 
       COUNT(*) AS n_rentals,
       COUNT(rating) AS n_ratings
FROM renting_extended
GROUP BY ROLLUP (genre, country);
| country  | genre  | n_rentals | n_ratings |
|----------|--------|-----------|-----------|
| null     | null   | 22        | 9         |
| Belgium  | Drama  | 15        | 6         |
| Austria  | Comedy | 2         | 1         |
| Belgium  | Comedy | 1         | 0         |
| Austria  | Drama  | 4         | 2         |
| null     | Comedy | 3         | 1         |
| null     | Drama  | 19        | 8         |
以資料驅動的 SQL 決策制定

一起來練習吧!

以資料驅動的 SQL 決策制定

Preparing Video For Download...