聚合函数扫描一组记录,然后返回单行记录。这组记录可以是一个表或者视图、或者一个子查询的结果。OceanBase 支持的聚合函数详情请参考《OceanBase SQL参考(Oracle模式)》。

    聚合函数通常跟 GROUP BY 子句一起使用,按照一个或多个列的值分组,然后每组返回单笔记录。

    示例:分组统计每个仓库的销售额

    Oracle 租户中,聚合函数跟 GROUP BY 子句一起使用时,select_list 中需要严格包含 GROUP BY 后面的列;否则会报错。SQL查询如下:

    1. SELECT ol_w_id
    2. , count(*) order_count
    3. , sum(ol_amount) sum_amount
    4. , round(avg(ol_amount),2) avg_amount
    5. , min(ol_amount) min_amount
    6. ,max(ol_amount) max_amount
    7. FROM ordl
    8. GROUP BY ol_w_id ORDER BY ol_w_id ;
    9. +---------+-------------+------------+------------+------------+------------+
    10. | OL_W_ID | ORDER_COUNT | SUM_AMOUNT | AVG_AMOUNT | MIN_AMOUNT | MAX_AMOUNT |
    11. +---------+-------------+------------+------------+------------+------------+
    12. | 1 | 297 | 917174.33 | 3088.13 | 0 | 9876.11 |
    13. | 2 | 329 | 1153354.23 | 3505.64 | 0 | 9979.34 |
    14. +---------+-------------+------------+------------+------------+------------+
    15. 2 rows in set (0.01 sec)
    16. SELECT ol_w_id, ol_d_id
    17. , count(*) order_count
    18. , sum(ol_amount) sum_amount
    19. , round(avg(ol_amount),2) avg_amount
    20. , min(ol_amount) min_amount
    21. ,max(ol_amount) max_amount
    22. FROM ordl
    23. GROUP BY ol_w_id
    24. ORDER BY ol_w_id;
    25. ERROR-00979: 'TPCC.ORDL.OL_D_ID' not a GROUP BY expression
    26. obclient>