2017-04-05 167 views
1

我需要在MariaDB中編寫一個SQL查詢來打印彙總值彙總行之間的報表。mariadb SQL查詢顯示彙總值彙總行

例如在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 

提前非常感謝。

+1

這類操作通常由應用程序的表示層進行。 –

+0

只需要寫一個sql。例如在Oracle中有「計算」命令 – arvind

回答

1

嘗試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修飾符文檔。

+0

感謝這工作,我想用「WITH ROLLUP」是在MariaDB中編寫這種查詢的最佳方式 – arvind

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

+0

謝謝,這是工作 – arvind