SQL JOIN COUNT和GROUP BY

时间:2018-05-28 11:28:59

标签: sql sql-server join

我有三张桌子 1. players(id, first_name, last_name, age, position, team_id) 2. teams(id, team_name, stadium, wins, draws,defeats,goal_for,goal_against) 3. goals_scored(id, player_id, goal_time)

SQL语句

SELECT
    players.first_name, 
    players.last_name,
    teams.name, 
    players.position, 
    players.age, 
    COUNT(*) AS goals 
FROM 
    players 
JOIN goals_scored
    ON players.id = goals_scored.player_id 
JOIN teams 
    ON players.team_id = teams.id 
GROUP BY players.id;

队伍表
id team_name stadium wins draws defeats goal_for goal_against 1 APF Club Dasharath 7 2 7 29 25

球员表
id first_name last_name position age team_id 4 Dipendra Shrestha forward 19 1

goals_scored表
id player_id goal_time 1 4 34 2 4 57

我想对玩家ID进行分组,以便我可以获得单个玩家的目标数。 像
first_name last_name team_name position age goals Dipendra Shrestha APF Club forward 19 2

我该怎么办?

2 个答案:

答案 0 :(得分:0)

您的查询基本上看起来很好。我会将GROUP BY调整为更完整:

SELECT p.first_name, p.last_name, t.name, p.position, p.age, 
       COUNT(*) AS goals 
FROM players p JOIN
     goals_scored gs
     ON p.id = gs.player_id JOIN
     teams t
     ON p.team_id = t.id 
GROUP BY p.first_name, p.last_name, t.name, p.position, p.age;

答案 1 :(得分:0)

希望尽可能少地对列进行分组,特别是如果涉及多个表,以便可以应用一个好的索引来处理该组。

WITH GoalsPerPlayer (playerId, nrOfGoals)
AS 
(
    SELECT player_id, count(*)
    FROM goals_scored 
    GROUP BY player_id
)
SELECT p.first_name, p.last_name, t.team_name, p.position, p.age, g.numberOfGoals as goals
FROM GoalsPerPlayer g
INNER JOIN players p ON p.id = g.player_id
INNER JOIN teams t ON t.id = p.team_id

修改

修正了PO在下面评论中提到的查询中的拼写错误。

WITH GoalsPerPlayer (playerId, nrOfGoals)
AS 
(
    SELECT player_id, count(*)
    FROM goals_scored 
    GROUP BY player_id
)
SELECT p.first_name, p.last_name, t.team_name, p.position, p.age, g.nrOfGoals as goals
FROM GoalsPerPlayer g
INNER JOIN players p ON p.id = g.playerId
INNER JOIN teams t ON t.id = p.team_id