日本熟妇hd丰满老熟妇,中文字幕一区二区三区在线不卡 ,亚洲成片在线观看,免费女同在线一区二区

GROUP BY

更新時間:

您可以使用GROUP BY子句根據指定的列對查詢結果進行分析,也可以在GROUP BY子句中使用GROUPING SETSCUBEROLLUP,以不同的形式展示分組結果。

GROUP BY expression [, ...]    

注意事項

  • 查詢中需使用標準聚合函數(SUMAVGCOUNT)聲明非分組列,若未聲明,則會使用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函數,其余兩列(LISTIDEVENTID)聲明為分組列。

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