views:

58

answers:

2

I'm sure this will equate down to the use of the COUNT statement but I'm not very good at SQL.

Here are my SQL Tables.

Teams Table:

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

Players Table:

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

What is the SQL (Miscroft SQL Server 2008) that will return the number of Players on each team?

output

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

I'd also like to return the RosterSpots and Team Id but really just the COUNT part above is what I'm puzzled with.

+2  A: 
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

Should do the trick, but feel free to rename the count column to something more friendly.

Modify to a LEFT JOIN to allow for teams with no players

PostMan
Still need to convert the NULL value into a zero, but I voted for the JOIN cuz looking for zero players is an assumption
OMG Ponies
You gotta reference the table being left joined--`PLAYERS`--in the COUNT. Any column in it...
OMG Ponies
Fixed :) thanks for that, you learn something everyday :)
PostMan
+5  A: 

Use:

   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
OMG Ponies
the LEFT JOIN makes sure that you also get teams without any players
Thilo
ahh yes good point - something I forgot...
PostMan
COALESCE? Now thats new to me. BRILLIANT! Thanks a ton for such a complete answer.
Justin
More points available cause I did have to make this slightly more complicated...http://stackoverflow.com/questions/3545660/how-do-i-join-a-third-table-in-my-sql-statement-which-returns-a-count-without-los
Justin