SQL Server RollUP | SQL CUBE的总和

时间:2018-08-21 22:12:20

标签: sql-server tsql

非常感谢您抽出宝贵时间提出一些建议/帮助。 我有下面的数据,我想使用SQL Server 2012按年份计算所有列组的总和。以下数据是四个国家/地区不同游戏的得分,我希望获得所有国家/地区的总得分一起(4个不同)按年分组。

SELECT 
,Country    
,SUM(Football)    AS Football
,SUM(Basket)      AS Basket
,SUM(Ball)        AS Ball
,SUM(Volleyball)  Volleyball    
,Year 
From CountryScore

GROUP BY 
 GROUP BY SETS(Year,())

样本数据

Raw Data

预期结果

Expected Answear

2 个答案:

答案 0 :(得分:0)

您可以尝试将SUM用于添加到期望的加法数字列中。

CREATE TABLE CountryScore(
   year int,
   Football int,
   Basket int,
  Volleyball int
); 

INSERT INTO CountryScore VALUES (1996,4,6,7);
INSERT INTO CountryScore VALUES (1996,4,6,7);
INSERT INTO CountryScore VALUES (1996,6,7,7);
INSERT INTO CountryScore VALUES (1996,6,7,7);
INSERT INTO CountryScore VALUES (2000,7,4,8);
INSERT INTO CountryScore VALUES (2000,7,6,5);
INSERT INTO CountryScore VALUES (2000,6,6,6);
INSERT INTO CountryScore VALUES (2000,6,8,8);

查询1

SELECT 
     [Year]    
    ,SUM(Football + Basket  + Volleyball) AS 'Total Score'
From CountryScore
GROUP BY 
     [Year]

DesktopFormFactor documentation

| Year | Total Score |
|------|-------------|
| 1996 |          74 |
| 2000 |          77 |

如果您的value列可能为NULL,则可以添加ISNULL函数以防止出现此情况,并将NULL设置为0。

SELECT 
     [Year]    
    ,SUM(ISNULL(Football,0) + ISNULL(Basket,0)  + ISNULL(Volleyball,0)) AS 'Total Score'
From CountryScore
GROUP BY 
     [Year]

答案 1 :(得分:0)

如果您想明智地玩游戏,则可以使用以下查询

选择年份,总和(足球),足球,总和(篮球),篮球,总和(排球)排球 来自#CountryScore 按分组(年,())分组

谢谢 萨西