首批通过分布式安全可靠测评,为关键业务系统打造
查询中使用聚合函数
更新时间:2026-06-16 15:13:49
聚合函数扫描一组记录,然后返回单行记录。这组记录可以是一个表或者视图、或者一个子查询的结果。OceanBase 支持的聚合函数详情请参考《OceanBase SQL 语句(Oracle模式)》。
聚合函数通常跟 GROUP BY 子句一起使用,按照一个或多个列的值分组,然后每组返回单笔记录。
示例
统计玩具订单的销售额。
创建示例表
toys_order_ny,并录入订单数据。obclient> CREATE TABLE toys_order_ny ( order_id NUMBER, toy_id NUMBER, toy_dealer VARCHAR2(20), toy_price NUMBER, toy_amount NUMBER ); Query OK, 0 rows affected插入
toys_order_ny表数据。obclient> INSERT INTO toys_order_ny VALUES ( 1001,1, 'A',53.12,100 ), ( 1002,2, 'A',24.8,190 ),( 1003,3, 'A',19.9,330) ,( 1004,1, 'B',53.12,50 ),( 1005,2, 'B',24.8,200 ), ( 1006,3, 'B',19.9,350 ),( 1007,2, 'A',24.8,100 ); 7 rows in set用聚合函数统计玩具订单的销售额。
obclient> SELECT toy_id , count(*) order_count , sum(toy_amount) sum_amount , round(avg(toy_amount),2) avg_amount , min(toy_amount) min_amount ,max(toy_amount) max_amount FROM toys_order_ny GROUP BY toy_id ORDER BY toy_id; +--------+-------------+------------+------------+------------+------------+ | toy_id | order_count | sum_amount | avg_amount | min_amount | max_amount | +--------+-------------+------------+------------+------------+------------+ | 1 | 2 | 150 | 75.00 | 50 | 100 | | 2 | 3 | 490 | 163.33 | 100 | 200 | | 3 | 2 | 680 | 340.00 | 330 | 350 | +--------+-------------+------------+------------+------------+------------+ 3 rows in set
有关 OceanBase 数据库当前版本所支持的聚合函数详情,请参见手册 《OceanBase 数据库 SQL 语句(Oracle 模式)》。