GROUP BY
更新時間:
您可以使用GROUP BY
子句根據指定的列對查詢結果進行分析,也可以在GROUP BY
子句中使用GROUPING SETS
、CUBE
或ROLLUP
,以不同的形式展示分組結果。
GROUP BY expression [, ...]
注意事項
查詢中需使用標準聚合函數(
SUM
、AVG
或COUNT
)聲明非分組列,若未聲明,則會使用ARBITRARY
函數聲明非分組列。GROUP BY
中的列或表達式列表必須與查詢列表中的非聚合表達式的列相同。
GROUPING SETS
GROUPING SETS
用于在同一結果集中指定多個GROUP BY
選項,作用相當于多個GROUP BY
查詢的UNION
組合形式。
SELECT origin_state, origin_zip, destination_state, sum(package_weight)
FROM shipping
GROUP BY GROUPING SETS (
(origin_state),
(origin_state, origin_zip),
(destination_state));
上述示例等同于:
SELECT origin_state, NULL, NULL, sum(package_weight)
FROM shipping GROUP BY origin_state
UNION ALL
SELECT origin_state, origin_zip, NULL, sum(package_weight)
FROM shipping GROUP BY origin_state, origin_zip
UNION ALL
SELECT NULL, NULL, destination_state, sum(package_weight)
FROM shipping GROUP BY destination_state;
CUBE
CUBE
用于列出所有可能的分組集。
SELECT origin_state, destination_state, sum(package_weight)
FROM shipping
GROUP BY origin_state, destination_state WITH CUBE
上述示例等同于:
SELECT origin_state, destination_state, sum(package_weight)
FROM shipping
GROUP BY GROUPING SETS (
(origin_state, destination_state),
(origin_state),
(destination_state),
())
ROLLUP
ROLLUP
可以以層級的方式列出分組集。
重要
AnalyticDB for MySQL不支持GROUP BY ROLLUP ()
后加列名。如果您想以層級方式實現GROUP BY
查詢的UNION
組合,可以通過GROUP BY GROUPING SETS ((column1, column2), (column1), ()) ,column3;
實現。
SELECT origin_state, origin_zip, SUM(package_weight)
FROM shipping
GROUP BY ROLLUP (origin_state, origin_zip)
上述示例等同于:
SELECT origin_state, origin_zip, sum(package_weight)
FROM shipping
GROUP BY GROUPING SETS ((origin_state, origin_zip), (origin_state), ())
示例
以下查詢列表中包含兩個聚合表達式,第一個聚合表達式使用SUM
函數,第二個聚合表達式使用COUNT
函數,其余兩列(LISTID
、EVENTID
)聲明為分組列。
SELECT listid, eventid, SUM(pricepaid) as revenue,
count(qtysold) as numtix
FROM sales
GROUP BY listid, eventid
ORDER BY 3, 4, 2, 1
LIMIT 5;
返回結果如下:
listid | eventid | revenue | numtix
-------+---------+---------+--------
89397 | 47 | 20.00 | 1
106590 | 76 | 20.00 | 1
124683 | 393 | 20.00 | 1
103037 | 403 | 20.00 | 1
147685 | 429 | 20.00 | 1
(5 rows)
GROUP BY
子句中的表達式也可以使用序號來引用所需的列。上述示例可改寫為以下形式。
SELECT listid, eventid, SUM(pricepaid) as revenue,
count(qtysold) as numtix
FROM sales
GROUP BY 1,2
ORDER BY 3, 4, 2, 1
LIMIT 5;
返回結果如下:
listid | eventid | revenue | numtix
-------+---------+---------+--------
89397 | 47 | 20.00 | 1
106590 | 76 | 20.00 | 1
124683 | 393 | 20.00 | 1
103037 | 403 | 20.00 | 1
147685 | 429 | 20.00 | 1
文檔內容是否對您有幫助?