Kategorien:

Abfragesyntax

GROUP BY ROLLUP

GROUP BY ROLLUP ist eine Erweiterung der GROUP BY-Klausel, die aggregierte Zeilen auf mehreren Ebenen einer Hierarchie erzeugt (zusätzlich zu den detaillierten gruppierten Zeilen). Wenn Sie beispielsweise nach Ort und Bundesstaat gruppieren, erstellt ROLLUP Aggregationen für jede Ort/Bundesstaat-Kombination, für jeden Bundesstaat insgesamt sowie eine Gesamtsumme über alle Bundesstaaten hinweg. Diese Aggregationen werden mit den gleichen Aggregatfunktionen berechnet, die in der SELECT-Klausel angegeben sind.

ROLLUP kann mit anderen GROUP BY-Ausdrücken kombiniert werden. Sie können zum Beispiel GROUP BY x, ROLLUP(y, z) schreiben, um nach Spalte x``in Kombination mit Rollup-Aggregationen für ``y und z zu gruppieren.

Sie können sich ein Rollup als das Generieren mehrerer Resultsets vorstellen, von denen jedes (nach der ersten) das Aggregat des vorherigen Resultsets ist. Wenn Sie zum Beispiel eine Einzelhandelskette besitzen, möchten Sie sich vielleicht den Gewinn anzeigen für:

  • Jede Filiale.

  • Jede Stadt (große Städte verfügen möglicherweise über mehrere Filialen).

  • Jeden Bundesstaat.

  • Alle (alle Filialen in allen Bundesstaaten).

Sie können separate Berichte erstellen, um diese Informationen abzurufen. Effizienter ist es jedoch, die Daten einmal zu scannen.

If you are familiar with the concept of grouping sets, you can think of a ROLLUP grouping as equivalent to a series of grouping sets, but essentially a shorter specification. The N elements of a ROLLUP specification correspond to N+1 GROUPING SETS.

See also

Syntax

SELECT ...
FROM ...
[ ... ]
GROUP BY [ groupItem [ , groupItem [ , ... ] ] , ] ROLLUP ( groupItem [ , groupItem [ , ... ] ] )
[ ... ]
Copy

Wobei:

groupItem ::= { <column_alias> | <position> | <expr> }
Copy

Parameter

column_alias

Spaltenalias, der in der Liste SELECT des Abfrageblocks angezeigt wird.

position

Position eines Ausdrucks in der Liste SELECT.

expr

Jeder Ausdruck in Tabellen im aktuellen Bereich.

Nutzungshinweise

  • As the query is aggregated at higher and higher levels, it shows NULL values in more columns of each row. This is appropriate. In the following example, for the aggregate at the state level, the city column is NULL; that’s because the value in the profit column does not correspond to one city. Similarly, in the final total, which aggregates data from all the states and all the cities, the revenue is not from one specific state or one specific city, so both the state and city columns in that row are NULL.

  • The query should list the „most significant level“ first in the parentheses after the ROLLUP. For example, states contain cities, so if you are rolling up data across states and cities, the clause should be GROUP BY ROLLUP (state, city)

    If you reverse the order of the column names, you get a result that is probably not what you want. In the following example, if you reversed the order of city and state in the ROLLUP clause, the result would be incorrect, at least in part because both California and Puerto Rico have a city named San Jose (SJ), and you probably would not want to combine the revenue from the two different San Jose cities, except in the final total of all revenue. (An alternative way to avoid combining data from different cities with the same name is to create a unique ID for each city and use the ID rather than the name in the query.)

  • Die Dienstprogrammfunktion GROUPING kann helfen, zwischen NULL-Werten, die sich aus der Rollup-Aggregation ergeben, und den tatsächlichen NULL-Werten in den Daten zu unterscheiden. GROUPING gibt 0 für eine Zeile zurück, die nach einer bestimmten Spalte gruppiert ist, und 1 für eine Zeile, in der die Spalte aufgrund der Aggregation NULL anzeigt.

Beispiele

Start by creating and loading a table with information about sales at a chain store that has branches in different cities and states/territories.

-- Create some tables and insert some rows.
CREATE TABLE products (product_ID INTEGER, wholesale_price REAL);
INSERT INTO products (product_ID, wholesale_price) VALUES 
    (1, 1.00),
    (2, 2.00);

CREATE TABLE sales (product_ID INTEGER, retail_price REAL, 
    quantity INTEGER, city VARCHAR, state VARCHAR);
INSERT INTO sales (product_id, retail_price, quantity, city, state) VALUES 
    (1, 2.00,  1, 'SF', 'CA'),
    (1, 2.00,  2, 'SJ', 'CA'),
    (2, 5.00,  4, 'SF', 'CA'),
    (2, 5.00,  8, 'SJ', 'CA'),
    (2, 5.00, 16, 'Miami', 'FL'),
    (2, 5.00, 32, 'Orlando', 'FL'),
    (2, 5.00, 64, 'SJ', 'PR');
Copy

Run a rollup query that shows profit by city, state, and total across all states. The query produces three „levels“ of aggregation:

  • Die einzelnen Städte.

  • Jeden Bundesstaat.

  • All revenue combined across all states.

The query uses ORDER BY state, city NULLS LAST to ensure that each state’s rollup comes immediately after all of the cities in that state, and that the final rollup appears at the end of the output.

SELECT state, city, SUM((s.retail_price - p.wholesale_price) * s.quantity) AS profit 
 FROM products AS p, sales AS s
 WHERE s.product_ID = p.product_ID
 GROUP BY ROLLUP (state, city)
 ORDER BY state, city NULLS LAST
 ;
+-------+---------+--------+
| STATE | CITY    | PROFIT |
|-------+---------+--------|
| CA    | SF      |     13 |
| CA    | SJ      |     26 |
| CA    | NULL    |     39 |
| FL    | Miami   |     48 |
| FL    | Orlando |     96 |
| FL    | NULL    |    144 |
| PR    | SJ      |    192 |
| PR    | NULL    |    192 |
| NULL  | NULL    |    375 |
+-------+---------+--------+
Copy

Einige Rollup-Zeilen enthalten NULL-Werte. Die letzte Zeile in der Tabelle enthält beispielsweise einen NULL-Wert für den Ort und einen NULL-Wert für den Bundesstaat, da die Daten für alle Orte und Bundesstaaten und nicht für einen bestimmten Ort und einen bestimmten Bundesstaat vorliegen.