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)
    • 各国家×各类型的租赁数
    • 各国家的租赁数
    • 租赁总数
  • 每一步降低一个明细层级
  • 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 进行数据驱动决策

Passons à la pratique !

用 SQL 进行数据驱动决策

Preparing Video For Download...