Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 连接两个表时如何使用计数_Sql Server - Fatal编程技术网

Sql server 连接两个表时如何使用计数

Sql server 连接两个表时如何使用计数,sql-server,Sql Server,我有两张桌子 第一个表tblHostel它包含三个这样的字段 酒店名称、房间号、容量和内容都是这样 HostelName室友容量 Vivakanand 1-12 Vivakanand 1-2 1 维瓦卡南德1-3 3 第二个表是tblStudent,有三个字段UserId,RoomId,HostelName,数据如下 HostelName RoomId UserId Vivakanand 1-1 101 Vivakanand 1-1102 维瓦卡南德1-3 103 我想以这样的方式合并这两个表,

我有两张桌子 第一个表tblHostel它包含三个这样的字段 酒店名称、房间号、容量和内容都是这样

HostelName室友容量
Vivakanand 1-12
Vivakanand 1-2 1
维瓦卡南德1-3 3

第二个表是tblStudent,有三个字段UserId,RoomId,HostelName,数据如下

HostelName RoomId UserId
Vivakanand 1-1 101
Vivakanand 1-1102
维瓦卡南德1-3 103

我想以这样的方式合并这两个表,我发现以下类型的输出

HostelName室友容量计数
Vivakanand 1-12
维瓦卡南德1-3 1

计数表统计tblStudent中的房间id。 对于单个表,我通过以下命令找到该输出
按RoomId,hotel从TBL学生组中选择RoomId,hotelname,count(RoomId)


但是我如何合并这两个表以实现所需的输出,我也使用join,但我无法实现

您需要首先根据HostelName和RoomID加入表,然后使用
COUNT
函数获取每个房间的学生人数,如下所示:

select h.hostelname, h.roomid, h.capacity, count(s.userid) Count
from tblhostel h 
inner join tblstudent s on h.hostelname = s.hostelname 
and h.roomid = s.roomid
group by h.hostelname, h.roomid, h.capacity