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);
  • 集計レベル
    • 国×ジャンルごとの集計
    • 国ごとの集計
    • 総集計
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)
    • 各国×各ジャンルのレンタル数
    • 各国のレンタル数
    • 総レンタル数
  • 各段階で詳細レベルを1つずつ落とす
  • 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で進めるデータドリブンな意思決定

Ayo berlatih!

SQLで進めるデータドリブンな意思決定

Preparing Video For Download...