ROLLUP

Datadriven beslutsfattning i SQL

Bart Baesens

Professor Data Science and Analytics

Tabell renting_extended

De första raderna i tabellen 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      |
| .......... | ........ | ...... | ...... |
Datadriven beslutsfattning i SQL

Fråga med ROLLUP

SELECT country, 
       genre, 
       COUNT(*)
FROM renting_extended
GROUP BY ROLLUP (country, genre);
  • Aggregeringsnivåer
    • Aggregering för varje kombination av land och genre
    • Aggregering per land
    • Total aggregering
Datadriven beslutsfattning i SQL

Fråga med 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     |
Datadriven beslutsfattning i SQL

Ordning i 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    |
Datadriven beslutsfattning i SQL

Sammanfattning ROLLUP

  • Returnerar aggregat för en hierarki av värden, t.ex. ROLLUP (country, genre)
    • Filmuthyrningar per land och genre
    • Filmuthyrningar per land
    • Totalt antal filmuthyrningar
  • För varje steg tas en detaljnivå bort
  • Kolumnordningen är viktig för ROLLUP
Datadriven beslutsfattning i SQL

Antal uthyrningar och betyg

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         |
Datadriven beslutsfattning i SQL

Nu kör vi en övning!

Datadriven beslutsfattning i SQL

Preparing Video For Download...