SQL在同一个表中为同一ID计数多个列

时间:2014-11-26 20:56:39

标签: sql-server count multiple-columns

我有一个包含GameID, GoalID, PlayerID, Assist1ID, Assist2ID列(全部整数)的表。 PlayerID翻译为实际得分的人的ID,但Assist1IDAssist2ID也会获得玩家ID。

我正在尝试获取具有不同PlayerID的数据集(来自PlayerID列或任一辅助列),目标计数(PlayerID列)和辅助计数(当Assist1发生时,实际上是计数列Assist2playerID的总和)。 PlayerID永远不会出现在其中一列中。

我一直在尝试几种方法,主要是使用UNION ALL,以及一些SUM / CASE,但我只是没有得到它。我应该为此使用临时表,还是有办法检查行,以及PlayerID

示例:(请注意GoalIDGameID在这种情况下并不重要)

GameID | GoalID | PlayerID   | Assist1ID | Assist2ID
  1    |    1   |     1876   |   2098    |     1097 
  1    |    2   |     2098   |   1829    |     1876 
  1    |    3   |     2098   |   1876    |     ---- 

我的查询应该返回:

PlayerID | Goals   | Assists
 1876    |    1    |    2
 2098    |    2    |    1
 1829    |    0    |    1
 1097    |    0    |    1

这实际上是可行的,还是我必须在代码部分做一些工作?

3 个答案:

答案 0 :(得分:1)

可以这样做,但我觉得可能有一个更简单的解决方案。

SELECT PlayerID, SUM(Goals), SUM(Assists)
FROM (
    SELECT PlayerID,Count(*) AS Goals,0 AS Assists FROM Goals GROUP BY PlayerID UNION ALL
    SELECT Assist1ID,0,Count(*) FROM Goals GROUP BY Assist1ID UNION ALL 
    SELECT Assist2ID,0,Count(*) FROM Goals GROUP BY Assist2ID
) T
WHERE NOT PlayerID IS NULL
GROUP BY PlayerID

答案 1 :(得分:1)

为确保您获得所涉及的每个玩家的结果记录,无论他们是只玩过,只是协助还是两者兼而有之,您必须三次完成数据并将记录与UNION ALL粘合在一起。算一算。

select playerid, sum(goal) as goals, sum(assist) as assists
from
(
  select playerid, 1 as goal, 0 as assist from mytable
  union all
  select assist1id, 0 as goal, 1 as assist from mytable
  union all
  select assist2id, 0 as goal, 1 as assist from mytable
)
group by playerid;  

答案 2 :(得分:0)

SELECT x.playerid
     , SUM(y.playerid = x.playerid) goals
     , SUM(x.playerid IN (y.assist1id,y.assist2id)) assists
  FROM 
     ( SELECT playerID FROM my_table 
        UNION 
       SELECT assist1id FROM my_table 
        UNION  
       SELECT assist2id FROM my_table
     ) x
  LEFT
  JOIN my_table y
    ON x.playerid IN(y.playerid,y.assist1id,y.assist2id)
 WHERE x.playerid IS NOT NULL
 GROUP
    BY playerid;