mariadb SQL查询显示具有聚合值的汇总行

时间:2017-04-05 06:12:55

标签: mysql mariadb

我需要在MariaDB中编写一个SQL查询,以便在带有聚合值的汇总行之间打印报告。

e.g。 EMP表中的数据是:

EmpName    ROLE         SALARY
A          Manager      10000
B          operator      8000
C          operator      8500
D          GM           20000
E          Manager       9000

我需要一个输出:

ROLE       EmpName    SALARY
Manager    A          10000
           E           9000
TOTAL                 19000
----------------------------
GM         D          20000
TOTAL                 20000 
----------------------------
operator   B           8000
           C           8500
TOTAL                 16500

非常感谢提前。

2 个答案:

答案 0 :(得分:2)

以下查询可以生成类似于您想要的输出:

SELECT IF(type = 1, ROLE, 'TOTAL'), SALARY
FROM (
   SELECT ROLE, SALARY, 1 AS type
   FROM mytable

   UNION ALL

   SELECT ROLE, SUM(SALARY) AS TotalSalary, 2 AS type
   FROM mytable
   GROUP BY ROLE) AS t
ORDER BY ROLE, type  

Demo here

答案 1 :(得分:1)

尝试使用WITH ROLLUP修饰符,例如 -

SELECT
  role, empname, SUM(salary)
FROM
  table1
GROUP BY
  role, empname WITH ROLLUP;

输出:

GM        D       20000
GM        (null)  20000
Manager   A       10000
Manager   E       9000
Manager   (null)  19000
operator  B       8000
operator  C       8500
operator  (null)  16500
(null)    (null)  55500

分组列的所有NULL值都是总值。最后一行是所有工资的总值。

GROUP BY WITH ROLLUP修饰符文档。