一组的SQL总和

时间:2017-06-29 22:06:55

标签: sql

我需要帮助在sql中获取组的总和。这是我的表格:

Sport         NumberOfPlayers
soccer          10
football        5
football        11 
baseball        6 
Tennis          8

这就是我想要的样子:

Sport         NumberOfPlayers      SumOfSport
soccer             10                 15 
football           5                  16
football           11                 16
baseball           6                  6
Tennis             8                  8
soccer             5                  15

4 个答案:

答案 0 :(得分:2)

您没有指定DBMS,因此这是使用窗口函数执行此操作的标准ANSI SQL:

select Sport, 
       NumberOfPlayers, 
       sum(NumberOfPlayers) over (partition by sport) as SumOfSport
from the_table;

答案 1 :(得分:1)

使用CROSS APPLY语句对sport分组的运动表的每一行上的球员进行聚合,使用WHERE子句过滤CROSS APPLY的结果,只返回第一个查询的聚合。 OUTER APPLY与第一个查询中的相同。

SELECT * FROM
(SELECT a.Sport, a.NumberOfPlayers FROM SportTable) as a

CROSS APPLY

(
SELECT Sum(b.NumberOfPlayers) as SumOfSport
FROM SportTable as b
WHERE a.Sport = b.Sport
GROUP BY b.Sport
) as b

答案 2 :(得分:0)

创建一个表格,其中包含每项运动的玩家总数,并称之为sumPlayer(或任何您喜欢的)。然后使用sumPlayer将表连接起来。

CREATE TABLE sport(
    sport_name varchar(10),
    numberOfPlayers int
)

INSERT INTO sport (sport_name, numberOfPlayers)
VALUES ('soccer', 10),
('football', 5),
('football', 11),
('baseball', 6),
('Tennis', 8),
('soccer', 15)

SELECT sport.sport_name, sumPlayer.totalPlayer 
FROM sport LEFT JOIN (
    SELECT sport_name, SUM(numberOfPlayers) AS totalPlayer
    FROM sport
    GROUP BY sport_name ) sumPlayer ON sumPlayer.sport_name = sport.sport_name

然后结果如下:

sport_name  numberOfPlayers
soccer      10
football    5
football    11
baseball    6
Tennis      8
soccer      5

希望这会有所帮助,您应该查看GROUP BY statement。在一般意义上,如果你要使用聚合函数,例如(COUNT,MAX,MIN,SUM,AVG),那么GROUP BY应该是你第一次去。

答案 3 :(得分:0)

另一种方法是使用Temp Table#Temp0创建所需的临时结构,然后使用另一个查询来更新总计:

SELECT  [Sport]
        ,[numberOfPlayers]
        ,0 [SumOfSport]
  INTO #Temp0    
  FROM Table1      

Update #Temp0 
SET [SumOfSport] =
     (
     SELECT SUM(numberOfPlayers)
     FROM #Temp0 T1
     WHERE #Temp0.Sport = T1.sport 
     group BY Sport 
     )

SELECT * from   #Temp0 
DROP Table #Temp0 
  • 请注意(正如@a_horse_with_no_name所指出的)此语法对于T-SQL(MS)是正确的。其他RDBMS可能需要一些语法调整。