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

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

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

    MySQL 租户中,聚合函数跟 GROUP BY 子句一起使用的时候,对 select_list 里的列没有要求。这个可能会导致结果集很奇怪。如果要求 select_list 里的列跟 GROUP BY 子句中的列保持一致,需要设置 MySQL 命令行下的 sql_mode 为 ‘ONLY_FULL_GROUP_BY’。SQL 查询如下:

    1. obclient> 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
    9. ORDER BY ol_w_id ;
    10. +---------+-------------+------------+------------+------------+------------+
    11. | ol_w_id | order_count | sum_amount | avg_amount | min_amount | max_amount |
    12. +---------+-------------+------------+------------+------------+------------+
    13. | 1 | 297 | 917174.33 | 3088.13 | 0.00 | 9876.11 |
    14. | 2 | 329 | 1153354.23 | 3505.64 | 0.00 | 9979.34 |
    15. +---------+-------------+------------+------------+------------+------------+
    16. 2 rows in set (0.01 sec)
    17. obclient> SELECT ol_w_id, ol_d_id
    18. , count(*) order_count
    19. , sum(ol_amount) sum_amount
    20. , round(avg(ol_amount),2) avg_amount
    21. , min(ol_amount) min_amount
    22. , max(ol_amount) max_amount
    23. FROM ordl
    24. GROUP BY ol_w_id
    25. ORDER BY ol_w_id
    26. ;
    27. +---------+---------+-------------+------------+------------+------------+------------+
    28. | ol_w_id | ol_d_id | order_count | sum_amount | avg_amount | min_amount | max_amount |
    29. +---------+---------+-------------+------------+------------+------------+------------+
    30. | 1 | 1 | 297 | 917174.33 | 3088.13 | 0.00 | 9876.11 |
    31. | 2 | 1 | 329 | 1153354.23 | 3505.64 | 0.00 | 9979.34 |
    32. +---------+---------+-------------+------------+------------+------------+------------+
    33. 2 rows in set (0.00 sec)
    34. obclient> show variables like '%sql_mode%';
    35. +---------------+-------------------------------------------------------+
    36. | Variable_name | Value |
    37. +---------------+-------------------------------------------------------+
    38. | sql_mode | PIPES_AS_CONCAT,STRICT_TRANS_TABLES,STRICT_ALL_TABLES |
    39. +---------------+-------------------------------------------------------+
    40. 1 row in set (0.00 sec)
    41. obclient> SET SESSION sql_mode='STRICT_ALL_TABLES,ONLY_FULL_GROUP_BY'; Query OK, 0 rows affected (0.00 sec)
    42. obclient> SELECT ol_w_id, ol_d_id
    43. , count(*) order_count
    44. , sum(ol_amount) sum_amount
    45. , round(avg(ol_amount),2) avg_amount
    46. , min(ol_amount) min_amount
    47. , max(ol_amount) max_amount
    48. FROM ordl
    49. GROUP BY ol_w_id
    50. ORDER BY ol_w_id
    51. ;
    52. ERROR 1055 (42000): 'tpccdb.ordl.ol_d_id' is not in GROUP BY
    53. obclient>