Kategorien:

Abfragesyntax

GROUP BY

Gruppiert Zeilen mit denselben Ausdrücken zum Gruppieren nach Elementen und berechnet Aggregatfunktionen für die resultierende Gruppe. Ein GROUP BY-Ausdruck kann Folgendes sein:

  • Ein Spaltenname.

  • Eine Nummer, die auf eine Position in der SELECT-Liste verweist.

  • Ein allgemeiner Ausdruck.

GROUP BY extensions

GROUP BY unterstützt die folgenden Erweiterungen, die leistungsstarke Aggregationsmöglichkeiten bieten:

  • GROUP BY GROUPING SETS: Berechnen mehrerer GROUP BY-Klauseln in einer einzigen -Anweisung

  • GROUP BY ROLLUP: Erzeugen von Zwischensummenzeilen für hierarchische Daten

  • GROUP BY CUBE : Erzeugen von Zwischensummenzeilen für alle Kombinationen von Dimensionen

Sie können diese Erweiterungen mit regulären GROUP BY-Spalten kombinieren. Beispiel:

  • GROUP BY x, GROUPING SETS(y, z)

  • GROUP BY x, ROLLUP(y, z)

  • GROUP BY x, CUBE(y, z)

Weitere Informationen zum Interpretieren von NULL-Werten in Erweiterungsergebnissen finden Sie in der Dokumentation zur GROUPING-Dienstprogrammfunktion.

Syntax

SELECT ...
  FROM ...
  [ ... ]
  GROUP BY groupItem [ , groupItem [ , ... ] ]
  [ ... ]
Copy
SELECT ...
  FROM ...
  [ ... ]
  GROUP BY ALL
  [ ... ]
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.

GROUP BY ALL

Gibt an, dass alle Elemente in der SELECT-Liste, die keine Aggregatfunktionen verwenden, für das Gruppieren verwendet werden sollen.

Beispiele finden Sie unter Gruppieren nach allen Spalten.

Nutzungshinweise

  • A GROUP BY clause can reference expressions in the projection clause by name or by position. If the GROUP BY clause references by name, each reference is resolved as follows:

    • If the query contains a database object (for example, a table or view) with a matching column name, the reference is resolved to the column name.

    • Otherwise, if the projection clause of the SELECT contains an expression alias with a matching name, the reference is resolved to the alias.

    Ein Beispiel dazu finden Sie unter Precedence when a column name and an alias match.

  • Wenn alle SELECT-Elemente Aggregatfunktionen verwenden, ist die Angabe von GROUP BY ALL gleichbedeutend mit der Angabe der Anweisung ohne GROUP BY-Klausel.

    Die folgende Anweisung enthält zum Beispiel nur SELECT-Elemente, die Aggregatfunktionen verwenden:

    SELECT SUM(amount)
      FROM mytable
      GROUP BY ALL;
    
    Copy

    Die obige Anweisung ist gleichbedeutend mit der Nichtangabe der GROUP BY-Klausel:

    SELECT SUM(amount)
      FROM mytable;
    
    Copy

Beispiele

Die folgenden Abschnitte enthalten Beispiele für die Verwendung der GROUP BY-Klausel:

Beachten Sie, dass die Beispiele in den einzelnen Abschnitten die Daten verwenden, die Sie unter Einrichten der Daten für die Beispiele eingerichtet haben.

Einrichten der Daten für die Beispiele

The examples in this section use a table named sales and a table named product. To create these tables and insert the data needed for the example, run the following commands:

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');

CREATE TABLE products (
  product_ID INTEGER,
  wholesale_price REAL);
INSERT INTO products (product_ID, wholesale_price) VALUES (1, 1.00);
INSERT INTO products (product_ID, wholesale_price) VALUES (2, 2.00);
Copy

Gruppieren nach einer Spalte

This example shows the gross revenue per product, grouped by product_id (that is, the total amount of money received for each product):

SELECT product_ID, SUM(retail_price * quantity) AS gross_revenue
  FROM sales
  GROUP BY product_ID;
Copy
+------------+---------------+
| PRODUCT_ID | GROSS_REVENUE |
+------------+---------------+
|          1 |          6    |
|          2 |        620    |
+------------+---------------+

Das folgende Beispiel baut auf dem vorherigen Beispiel auf und zeigt den Nettogewinn pro Produkt an, gruppiert nach product_id:

SELECT p.product_ID, 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 p.product_ID;
Copy
+------------+--------+
| PRODUCT_ID | PROFIT |
+------------+--------+
|          1 |      3 |
|          2 |    372 |
+------------+--------+

Gruppieren nach mehreren Spalten

Das folgende Beispiel veranschaulicht, wie Sie nach mehreren Spalten gruppieren können:

SELECT state, city, SUM(retail_price * quantity) AS gross_revenue
  FROM sales
  GROUP BY state, city;
Copy
+-------+---------+---------------+
| STATE |   CITY  | GROSS REVENUE |
+-------+---------+---------------+
|   CA  | SF      |            22 |
|   CA  | SJ      |            44 |
|   FL  | Miami   |            80 |
|   FL  | Orlando |           160 |
|   PR  | SJ      |           320 |
+-------+---------+---------------+

Gruppieren nach allen Spalten

Das folgende Beispiel entspricht dem unter Gruppieren nach mehreren Spalten verwendeten Beispiel.

SELECT state, city, SUM(retail_price * quantity) AS gross_revenue
  FROM sales
  GROUP BY ALL;
Copy
+-------+---------+---------------+
| STATE |   CITY  | GROSS REVENUE |
+-------+---------+---------------+
|   CA  | SF      |            22 |
|   CA  | SJ      |            44 |
|   FL  | Miami   |            80 |
|   FL  | Orlando |           160 |
|   PR  | SJ      |           320 |
+-------+---------+---------------+

Precedence when a column name and an alias match

It is possible (but usually not recommended) to create a query that contains an alias that matches a column name:

SELECT x, some_expression AS x
  FROM ...
Copy

If a clause contains a name that matches both a column name and an alias, then the clause uses the column name. The following example demonstrates this behavior using a GROUP BY clause:

Erstellen Sie eine Tabelle, und fügen Sie Zeilen ein:

CREATE TABLE employees (salary FLOAT, state VARCHAR, employment_state VARCHAR);
INSERT INTO employees (salary, state, employment_state) VALUES
  (60000, 'California', 'Active'),
  (70000, 'California', 'On leave'),
  (80000, 'Oregon', 'Active');
Copy

The following query returns the sum of the salaries of the employees who are active and the sum of the salaries of the employees who are on leave:

SELECT SUM(salary), ANY_VALUE(employment_state)
  FROM employees
  GROUP BY employment_state;
Copy
+-------------+-----------------------------+
| SUM(SALARY) | ANY_VALUE(EMPLOYMENT_STATE) |
|-------------+-----------------------------|
|      140000 | Active                      |
|       70000 | On leave                    |
+-------------+-----------------------------+

The next query uses the alias state, which matches the name of a column of the table in the query. When state is used in the GROUP BY clause, Snowflake interprets it as a reference to the column name, not the alias. This query therefore returns the sum of the salaries of the employees in the state of California and the sum of the salaries of the employees in the state of Oregon, yet displays employment_state information, such as Active, rather than the names of states or provinces:

SELECT SUM(salary), ANY_VALUE(employment_state) AS state
  FROM employees
  GROUP BY state;
Copy
+-------------+--------+
| SUM(SALARY) | STATE  |
|-------------+--------|
|      130000 | Active |
|       80000 | Active |
+-------------+--------+