我需要一条SQL语句,该语句返回具有特定值的表中的行数 [英] I need a SQL statement that returns the number rows in a table with a specific value

查看:197
本文介绍了我需要一条SQL语句,该语句返回具有特定值的表中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我确定这将等同于使用COUNT语句,但我对SQL的了解不是很好。



这是我的SQL表。 / p>

队表:



  TeamId TeamName RosterSpots 
- ---------------------------------------------
1迈阿密热火队12
2纽约尼克斯队10



玩家表:



  PlayerId PlayerName TeamId 
------------------------- -----------
1德怀恩·韦德1
2克里斯·波什1
3勒布朗·詹姆斯1
4阿玛雷·斯塔德迈尔2

什么是SQL(Miscroft SQL Server 2008),它将返回每个团队中的玩家人数?



输出

 团队名称PlayerCount 
-------- ---------------------
迈阿密热火3
纽约尼克斯1


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

解决方案

使用:

  SELECT t.teamid,
t.teamname,
COALESCE(COUNT(p.playerid),0)AS玩家数量,
t.rosterspots
来自团队t
左加入玩家p on .teamid
由t.teamid,t.teamname,t.rosterspots分配的组


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.

解决方案

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

这篇关于我需要一条SQL语句,该语句返回具有特定值的表中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆