聚合函数扫描一组记录,然后返回单行记录。这组记录可以是一个表或者视图、或者一个子查询的结果。OceanBase 支持的聚合函数详情请参考《OceanBase SQL参考(Oracle模式)》。
聚合函数通常跟 GROUP BY 子句一起使用,按照一个或多个列的值分组,然后每组返回单笔记录。
示例:分组统计每个仓库的销售额
Oracle 租户中,聚合函数跟 GROUP BY 子句一起使用时,select_list 中需要严格包含 GROUP BY 后面的列;否则会报错。SQL查询如下:
SELECT ol_w_id
, count(*) order_count
, sum(ol_amount) sum_amount
, round(avg(ol_amount),2) avg_amount
, min(ol_amount) min_amount
,max(ol_amount) max_amount
FROM ordl
GROUP BY ol_w_id ORDER BY ol_w_id ;
+---------+-------------+------------+------------+------------+------------+
| OL_W_ID | ORDER_COUNT | SUM_AMOUNT | AVG_AMOUNT | MIN_AMOUNT | MAX_AMOUNT |
+---------+-------------+------------+------------+------------+------------+
| 1 | 297 | 917174.33 | 3088.13 | 0 | 9876.11 |
| 2 | 329 | 1153354.23 | 3505.64 | 0 | 9979.34 |
+---------+-------------+------------+------------+------------+------------+
2 rows in set (0.01 sec)
SELECT ol_w_id, ol_d_id
, count(*) order_count
, sum(ol_amount) sum_amount
, round(avg(ol_amount),2) avg_amount
, min(ol_amount) min_amount
,max(ol_amount) max_amount
FROM ordl
GROUP BY ol_w_id
ORDER BY ol_w_id;
ERROR-00979: 'TPCC.ORDL.OL_D_ID' not a GROUP BY expression
obclient>