如何获得所有行的总结果? (对于 ORACLE )
SELECT
NAME,
SUM(CASE WHEN ASSIST_1 = 'YES' THEN 1 END) WEEK1,
SUM(CASE WHEN ASSIST_2 = 'YES' THEN 1 END) WEEK2,
SUM(CASE WHEN ASSIST_3 = 'YES' THEN 1 END) WEEK3,
FROM TABLE_NAME
WHERE GROUP BY NAME;
我有这样的结果: 名称周1周2周3
Anne 1 2 3
Bob 3 1 0
Charlie 4 5 1
我想要这个结果:
Anne 1 2 3
Bob 3 1 0
Charlie 4 5 1
Total 8 8 4
答案 0 :(得分:4)
如何获得所有行的总结果?
使用TZDIR
子句的rollup()
扩展名。像这样的东西(只是一个例子):
group by
结果:
-- sample of date from your question
with t1(uname, c1, c2, c3) as(
select 'Anne' , 1, 2, 3 from dual union all
select 'Bob' , 3, 1, 0 from dual union all
select 'Charlie', 4, 5, 1 from dual
)
-- actual query
select case grouping(uname)
when 0 then uname
else 'Total' end
as uname1
, sum(c1) as c1
, sum(c2) as c2
, sum(c3) as c3
from t1
group by rollup(uname)
order by grouping(uname)
答案 1 :(得分:0)
将UNION ALL
与SUM
值
WITH t1(name, week1, week2, week3) AS
( SELECT 'Anne', 1, 2, 3 FROM dual
UNION ALL
SELECT 'Bob', 3, 1, 0 FROM dual
UNION ALL
SELECT 'Charlie', 4, 5, 1 FROM dual
),
s AS
(SELECT 'Total' name,
SUM(week1) week1,
SUM(week2) week2,
SUM(week2) week3
FROM t1
)
SELECT * FROM t1
UNION ALL
SELECT * FROM s;
<强>结果:强>
NAME WEEK1 WEEK2 WEEK3
Anne 1 2 3
Bob 3 1 0
Charlie 4 5 1
Total 8 8 8
答案 2 :(得分:0)
基于@Nicholas回答:
SELECT
CASE GROUPING(NAME) WHEN 0 THEN NAME ELSE 'TOTAL' END AS NAME,
SUM (WEEK1) AS WEEK1,
SUM (WEEK2) AS WEEK2,
SUM (WEEK3) AS WEEK3
FROM (
SELECT
NAME,
SUM(CASE WHEN ASSIST_1 = 'YES' THEN 1 END) WEEK1,
SUM(CASE WHEN ASSIST_2 = 'YES' THEN 1 END) WEEK2,
SUM(CASE WHEN ASSIST_3 = 'YES' THEN 1 END) WEEK3,
FROM TABLE_NAME
WHERE GROUP BY (NAME)
GROUP BY ROLLUP(NAME)
ORDER BY GROUPING(NAME);
给出这个结果:
Anne 1 2 3
Bob 3 1 0
Charlie 4 5 1
Total 8 8 4