将列数据计算为一行

时间:2017-08-16 08:10:38

标签: sql

在SQL中:

想象一下一张桌子:

创建表A(F NVARCHAR(100),R1 INT,R2 INT,R3 INT)

F | R1 | R2| R3
A | 10 | 3 | 7
B | 5  | 4 | 6

我需要的结果集:

F | R1 | R2| R3
A | 10 | 3 | 7
B | 5  | 4 | 6
C | 15 | 7 | 13

其中C是A + B的结果,C是A和B之后的行

2 个答案:

答案 0 :(得分:3)

根据你的解释,我猜你需要总结所有行。

我想通过GROUP BY和ROLL UP,您可以设法获得正确的解决方案

尝试类似的东西:

SELECT F, SUM(R1), SUM(R2), SUM(R3)
FROM test
GROUP BY F WITH ROLLUP

Follow this link for a demo

更新:

我设法得到你在结果方面的要求: 试试这个(Works on SQL Server 2014)

SELECT F = ISNULL(F,'C'), SUM(R1) AS 'R1', SUM(R2) AS 'R2', SUM(R3) AS 'R3'
FROM test
GROUP BY F WITH ROLLUP

Follow this link for a demo

更新2(由Josh Gilfillan建议):

上一个不管理需要为null的行。

SELECT CASE WHEN GROUPING(F) = 1 THEN 'C' ELSE F END AS 'F', SUM(R1) AS 'R1', SUM(R2) AS 'R2', SUM(R3) AS 'R3'
FROM test
GROUP BY F WITH ROLLUP

Link to the demo

答案 1 :(得分:0)

SELECT * 
FROM A
WHERE F = 'A' OR F = 'B'
UNION ALL
SELECT 'C', 
(SELECT R1 FROM A WHERE F = 'A') + (SELECT R1 FROM A WHERE F = 'B'),
(SELECT R2 FROM A WHERE F = 'A') + (SELECT R2 FROM A WHERE F = 'B'),
(SELECT R3 FROM A WHERE F = 'A') + (SELECT R3 FROM A WHERE F = 'B')

DBFiddle