我有这个SQL查询,它执行GROUP BY将所有包含相同Player_id但不包含相同Game_id的行合并在一起:
SELECT p.Player_id,
p.Name,
p.Position,
SUM(s.Goals) AS goalsb,
SUM(s.Assists) AS assistsb,
SUM(s.Points) AS pointsb
FROM Dim_Player AS p
INNER JOIN Fact_Statistics AS s ON s.Player_id = p.Player_id
GROUP BY p.Player_id, p.Name, p.Position
ORDER BY pointsb DESC, goalsb DESC
我想要做的是每次GROUP BY将一行与另一行合并时,植入一个COUNT来创建一个名为“Games playing”的新列。例如:
Player_id Game_id goalsb
8470598 465 1
8470598 435 1
这将与上面的SQL查询组合在一起成为:
Player_id goalsb
8470598 2
但我想要这个:
Player_id goalsb Games_played
8470598 2 2
答案 0 :(得分:13)
如果您重复Game_id
并且想要计算不同的值,则可以添加
COUNT (DISTINCT Game_id)
子句到你的SELECT
陈述。
答案 1 :(得分:0)
向选择查询添加计数功能。 COUNT(*)计算组中的每一行,与所选列无关。
SELECT p.Player_id, p.Name, p.Position, SUM(s.Goals) AS goalsb, SUM(s.Assists) AS assistsb, SUM(s.Points) AS pointsb, COUNT(*) as [Games_played]
FROM Dim_Player AS p INNER JOIN Fact_Statistics AS s ON s.Player_id = p.Player_id
GROUP BY p.Player_id, p.Name, p.Position, s.Game_id
ORDER BY pointsb DESC, goalsb DESC