SQL server 2008
您好
这是我的查询,它返回结果
SELECT * FROM Rooms
WHERE RoomID in
(SELECT t1.RoomId FROM
(Rooms t1 INNER JOIN
(SELECT RoomID, SUM(quantity) AS QTY FROM Room_Item GROUP BY RoomID
HAVING SUM(Quantity) = 0) t2 ON t1.RoomID = t2.RoomID))
以上书面查询将返回房间的房间,其中没有任何项目(数量= 0), 但现在我想过滤掉建筑物的结果,
我得到了具体建筑的房间清单,如下所示
select roomid from rooms where buildingblockid in (select buidingblockid from buildingblock where buildigID = 1)
所以我的查询将是
从已分配项目为0的房间表返回房间,并按建筑物编号= 1
过滤房间表结构如下 - 仅显示基本字段
rooms => roomid(PK), buildingblockID(FK), roomname
room_item => roomitemid(PK), roomid(FK), itemid(FK), quantity
item => itemid(PK), itemname
buildingblock => buildingblockid(PK), buildingID(FK)
building => buildingID(PK), buildingName
答案 0 :(得分:1)
您可以创建派生表以查找没有项目的房间,并将其加入buildingWiseRoom以过滤建筑物。
select buildingWiseRoom.roomID
from buildingWiseRoom
inner join
(
select RoomID
from Room_Item
group by RoomID
having SUM(Quantity) = 0
) itemlessRooms
on buildingWiseRoom.roomID = itemlessRooms.roomID
where buildingWiseRoom.buildingID = 1
更新表格结构更新:
select rooms.roomID
from rooms
inner join buildingblock
on rooms.buildingblockID = buildingblock.buildingblockID
inner join
(
select RoomID
from Room_Item
group by RoomID
having SUM(Quantity) = 0
) itemlessRooms
on rooms.roomID = itemlessRooms.roomID
where buildingblock.buildingID = 1