我需要一个特定的值返回一个表中的行数SQL语句(I need a SQL statement tha

2019-10-29 07:15发布

我敢肯定,这将等同下来使用COUNT语句,但我不是在SQL非常好。

这里是我的SQL表。

团队表:

TeamId     TeamName           RosterSpots 
----------------------------------------------- 
1          Miami Heat         12 
2          New York Knicks    10 

玩家表:

PlayerId   PlayerName         TeamId 
------------------------------------ 
1          Dwyane Wade        1 
2          Chris Bosh         1 
3          LeBron James       1 
4          Amar'e Stoudemire  2 

什么是SQL(Miscroft的SQL Server 2008),将返回各队球员的数量?

产量

Team Name         PlayerCount
-----------------------------
Miami Heat        3
New York Knicks   1

我也想返回RosterSpots和团队ID但实际上只是上面的COUNT的部分是什么,我不解带。

Answer 1:

采用:

   SELECT t.teamid,
          t.teamname,
          COALESCE(COUNT(p.playerid), 0) AS playercount,
          t.rosterspots
     FROM TEAMS t
LEFT JOIN PLAYERS p ON p.teamid = t.teamid
 GROUP BY t.teamid, t.teamname, t.rosterspots


Answer 2:

SELECT t.TeamID, RosterSpots, TeamName, COALESCE(COUNT(p.PlayerID),0) 
FROM Teams t 
LEFT JOIN Players p on t.TeamID = p.TeamID
GROUP BY TeamName,t.TeamID, RosterSpots

应该做的伎俩,但随时计数列重命名为更友好。

修改为LEFT JOIN允许没有球员球队



文章来源: I need a SQL statement that returns the number rows in a table with a specific value