我一直试图以各种方式做到这一点,但无法得到确切的解决方案,所以任何帮助将不胜感激
来源:
Name ID Project SLA
Ab 1 App 100
bc 2 App 80
cd 3 Bap 200
Ef 4 Vap 30
Fg 5 Vap 70
目标:
Name ID Project SLA
Ab 1 App 100
bc 2 App 80
Null Null App 180
cd 3 Bap 200
Null Null Bap 200
Ef 4 Vap 30
Fg 5 Vap 70
Null Null Vap 100
在SQL中
答案 0 :(得分:2)
select Name, ID, Project, SLA
from tab
union all
select null, null, Project, SUM(SLA)
from tab
group by project
order by project, id
ANSI / ISO标准SQL,应该是可移植的。 (发布之前用几个不同的dbms标记了......)
答案 1 :(得分:0)
你可以使用这个:
WITH t AS
(SELECT NAME, ID, PROJECT, SUM(SLA) AS SUM_SLA, GROUPING_ID(NAME, ID) AS GROUPING_ID
FROM SLA
GROUP BY ROLLUP(NAME, ID), PROJECT)
SELECT NAME, ID, PROJECT, SUM_SLA
FROM t
WHERE GROUPING_ID IN (0,3);
甚至更紧凑
SELECT NAME, ID, PROJECT, SUM(SLA) AS SUM_SAL
FROM SLA
GROUP BY PROJECT, GROUPING SETS((NAME, ID), PROJECT);
但是,我不知道它是否受SQL-Server支持