How to count GROUP BY rows in T-SQL

百般思念 提交于 2019-12-10 13:56:04

问题


I have this SQL query that does a GROUP BY to merge together all rows that contain the same Player_id but not the same 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

What I want to do is implant a COUNT each time the GROUP BY merges a row with another to create a new column called "Games played". Example:

Player_id      Game_id    goalsb
8470598        465        1
8470598        435        1

this will be grouped together with the SQL query above to become:

Player_id          goalsb
8470598            2

But I want to have this:

Player_id          goalsb       Games_played
8470598            2            2

回答1:


If you have repeating Game_id's and you'd like to count the distinct values, you can add a

COUNT (DISTINCT Game_id)

clause to your SELECT statement.




回答2:


Add a count function to the select query. COUNT(*) counts each row in the group, independent of the columns selected.

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


来源:https://stackoverflow.com/questions/8548534/how-to-count-group-by-rows-in-t-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!