备注:测试数据库版本为MySQL 8.0
如需要scott用户下建表及录入数据语句,可参考:
scott建表及录入数据sql脚本
一.需求
定义一个“简单小计”结果集,它包含一列的聚集值以及全表的总计值。
例如将表emp中各job的工资总和放入一个结果集,并且将表emp总所有工资的总和也加入其中。
按job的工资是小计,而表emp中的工资总和是总计。
这样的结果集应该如下:
+-----------+----------+
| job | sal |
+-----------+----------+
| ANALYST | 6000.00 |
| CLERK | 4150.00 |
| MANAGER | 8275.00 |
| PRESIDENT | 5000.00 |
| SALESMAN | 5600.00 |
| TOTAL | 29025.00 |
+-----------+----------+
二.解决方案
group by子句的rollup拓展可以完美的解决这个问题。
select coalesce(job,'TOTAL') job,
sum(sal) sal
from emp
group by job with rollup;
测试记录:
mysql> select coalesce(job,'TOTAL') job,
-> sum(sal) sal
-> from emp
-> group by job with rollup;
+-----------+----------+
| job | sal |
+-----------+----------+
| ANALYST | 6000.00 |
| CLERK | 4150.00 |
| MANAGER | 8275.00 |
| PRESIDENT | 5000.00 |
| SALESMAN | 5600.00 |
| TOTAL | 29025.00 |
+-----------+----------+
6 rows in set, 1 warning (0.01 sec)
网友评论