我有水平的总数,我想要实现蓝色的最后一行,我使用了这个查询
SELECT
DepartmentName,
SUM(CASE WHEN Risk = 'High' THEN 1 ELSE 0 END) High,
SUM(CASE WHEN Risk = 'Medium' THEN 1 ELSE 0 END) Medium,
SUM(CASE WHEN Risk = 'Low' THEN 1 ELSE 0 END) Low,
SUM(CASE WHEN Risk = 'High' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN Risk = 'Medium' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN Risk = 'Low' THEN 1 ELSE 0 END) Total
FROM
TableName
GROUP BY
DepartmentName
我怎样才能获得最后一行?
答案 0 :(得分:1)
可以使用Grouping sets
完成此操作SELECT COALESCE(DepartmentName, 'Total'),
SUM(CASE WHEN Risk = 'High' THEN 1 ELSE 0 END) High,
SUM(CASE WHEN Risk = 'Medium' THEN 1 ELSE 0 END) Medium,
SUM(CASE WHEN Risk = 'Low' THEN 1 ELSE 0 END) Low,
SUM(CASE WHEN Risk = 'High' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN Risk = 'Medium' THEN 1 ELSE 0 END)
+ SUM(CASE WHEN Risk = 'Low' THEN 1 ELSE 0 END) Total
FROM TableName
GROUP BY GROUPING SETS ((DepartmentName), ())
答案 1 :(得分:0)
使用ROLLUP
SELECT
COALESCE(DepartmentName, 'Total') DepartmentName,
SUM(CASE WHEN Risk = 'High' THEN 1 ELSE 0 END) High,
SUM(CASE WHEN Risk = 'Medium' THEN 1 ELSE 0 END) Medium,
SUM(CASE WHEN Risk = 'Low' THEN 1 ELSE 0 END) Low,
SUM(CASE WHEN Risk IN ('High', 'Medium', 'Low') THEN 1 ELSE 0 END) Total
FROM table
GROUP BY DepartmentName with ROLLUP
答案 2 :(得分:0)
我能想到的最简单的
select Department, High, Medium, Low, Total from MY_TABLE
union all
select 'Total', sum(High), sum(Medium), sum(Low), sum(Total) from MY_TABLE