我有以下两个名为ROOM和SESSION的表。
ROOM
BUILDINGNO | ROOMNO | ROOMCAPACITY
-----------+--------+-------------
B1 | R1 | 121
B1 | R2 | 253
B2 | R1 | 275
B2 | R2 | 126
B2 | R3 | 124
B3 | R1 | 256
B3 | R2 | 324
B4 | R1 | 431
B4 | R2 | 345
B4 | R3 | 231
SESSION
SESSIONID | BUILDINGNO | ROOMNO | SPEAKERID
----------+------------+--------+----------
SS01 | B1 | R1 | S1
SS02 | B2 | R1 | S2
SS03 | B1 | R2 | S2
SS04 | B4 | R2 | S4
SS05 | B3 | R2 | S5
SS06 | B3 | R1 | S5
SS07 | B4 | R2 | S3
SS08 | B1 | R2 | S2
SS09 | B2 | R3 | S4
SS10 | B4 | R1 | S3
我希望能够显示每个房间的会话数量。理想情况下,这会显示出某种类似的表格。
BUILDINGNO | ROOMNO | NUMBEROFSESSIONS
-----------+--------+-----------------
B1 | R1 | 1
B1 | R2 | 2
B2 | R1 | 1
B2 | R2 | 0
B2 | R3 | 1
B3 | R1 | 1
B3 | R2 | 1
B4 | R1 | 1
B4 | R2 | 2
B4 | R3 | 0
我知道我需要在某个地方使用COUNT和JOIN功能......但我至少可以说有点卡住了。如果有人能指出我正确的方向或向我解释,我将不胜感激:)
SELECT BUILDINGNUMBER, ROOMNO FROM ROOM ... COUNT? ... JOIN?
还有什么可以让我显示/隐藏会话数= 0的行?
答案 0 :(得分:1)
如果您只对每个会议室内的会话数感兴趣,那么我相信您在 SESSION 表中有足够的信息。
SELECT BUILDINGNO, ROOMNO, COUNT(*)FROM SESSION
GROUP BY BUILDINGNO, ROOMNO;
答案 1 :(得分:0)
You could use count(distinct sessionid)
SELECT ROOM.BUILDINGNO , ROOM.ROOMNO, count(distinct SESSION.sessionid)
from ROOM
left join SESSION on ROOM.ROOMNO = SESSION.ROOMNO
and ROOM.BUILDINGNO = SESSION.BUILDINGNO
group by ROOM.BUILDINGNUMBER, ROOM.ROOMNO
and for hide room with resul = 0 you can use having
SELECT ROOM.BUILDINGNO , ROOM.ROOMNO, count(distinct SESSION.sessionid)
from ROOM
left join SESSION on ROOM.ROOMNO = SESSION.ROOMNO
and ROOM.BUILDINGNO = SESSION.BUILDINGNO
group by ROOM.BUILDINGNUMBER, ROOM.ROOMNO
HAVING count(distinct SESSION.sessionid) >0
but you have enough info in the tables sessions
SELECT SESSION.BUILDINGNO , SESSION.ROOMNO, count(distinct SESSION.sessionid)
SESSION
group by SESSION.BUILDINGNO , SESSION.ROOMNO
HAVING count(distinct SESSION.sessionid) >0
答案 2 :(得分:0)
SELECT r.BUILDINGNO, r.ROOMNO, count(1) QQ
FROM ROOM r, SESS s
WHERE
r.ROOMNO = s.ROOMNO
AND r.BUILDINGNO = s.BUILDINGNO
GROUP BY r.BUILDINGNO, r.ROOMNO
ORDER by r.BUILDINGNO;
[DEMO] [1] http://sqlfiddle.com/#!4/eb290/6