SQL Server 2008:计算新行中的SUM(分组依据)

时间:2014-12-17 17:05:50

标签: sql-server group-by sum

我有一张表格如下:

CREATE TABLE #tableA (color varchar(10), ids int, scores int)
INSERT INTO #tableA 
VALUES ('red', 1, 100),
('red',2,100),
('red',3,50),
('blue',1,20),
('blue',5,50)

我希望得到分数的总和,按颜色分组。预期结果:

color  id  scores
red    1   100
red    2   100
red    3    50
           SUM 250 (100+100+50)  
blue   1    20
blue   5    50
            SUM 70 (all blues)

由于

2 个答案:

答案 0 :(得分:2)

Group by

中使用ROllUP
SELECT *
FROM   (SELECT color,
               ids,
               Sum(scores)scores
        FROM   #tableA
        GROUP  BY color,
                  ids WITH rollup) a
WHERE  color IS NOT NULL
        OR ids IS NOT NULL 

答案 1 :(得分:2)

您可以使用GROUPING SETS,但结果不会直接采用您想要的格式:

SELECT  color, 
        ids, 
        SUM(scores) Scores
FROM #TableA
GROUP BY GROUPING SETS((color,ids),(color))

结果是:

╔═══════╦══════╦════════╗
║ color ║ ids  ║ Scores ║
╠═══════╬══════╬════════╣
║ blue  ║ 1    ║     20 ║
║ blue  ║ 5    ║     50 ║
║ blue  ║ NULL ║     70 ║
║ red   ║ 1    ║    100 ║
║ red   ║ 2    ║    100 ║
║ red   ║ 3    ║     50 ║
║ red   ║ NULL ║    250 ║
╚═══════╩══════╩════════╝