Use GROUP BY’s ROLLUP extension to produce a grand total for all salaries
along with the subtotals for each JOB:
Use the COEALESCE function against the JOB column. If the value of JOB is
NULL, the value for SAL is the grand total created by ROLLUP. If the value of JOB is not NULL,
the value for SAL is the result of the “regular” GROUP BY, not the ROLLUP:
방법1)
mysql> select coalesce(job, 'TOTAL') job, sum(sal) sal
-> from EMP
-> group by job with rollup;
+-----------+-------+
| job | sal |
+-----------+-------+
| ANALYST | 6000 |
| CLERK | 6850 |
| MANAGER | 9825 |
| PRESIDENT | 4000 |
| SALESMAN | 5600 |
| TOTAL | 32275 |
+-----------+-------+
6 rows in set, 1 warning (0.00 sec)
방법2)
mysql> select job, sum(sal) as sal
-> from EMP
-> group by job
-> union all
-> select 'TOTAL', sum(sal) from EMP;
+-----------+-------+
| job | sal |
+-----------+-------+
| ANALYST | 6000 |
| CLERK | 6850 |
| MANAGER | 9825 |
| PRESIDENT | 4000 |
| SALESMAN | 5600 |
| TOTAL | 32275 |
+-----------+-------+
6 rows in set (0.00 sec)
== Oracle
Use the ROLLUP extension to GROUP BY to produce a grand total for all
salaries along with the subtotals for each JOB:
Use the GROUPING function in the JOB column to display a label for the
grand total. If the value of JOB is NULL, the GROUPING function will return 1, which signifies
that the value for SAL is the grand total created by ROLLUP. If the value of JOB is not NULL,
the GROUPING function will return 0, which signifies the value for SAL is the result of the
GROUP BY, not the ROLLUP.
select case grouping(job)
when 0 then job
else 'TOTAL'
end job,
sum(sal) sal
from emp
group by rollup(job);