我认为OP删除了这个问题,措辞不当,并且措辞得很好,这简直令人遗憾;它提供了一个演示如何在SQL中使用 UNION 操作来动态构建有效执行操作所需的关系的机会:
原帖(如果以下OP评论请求,我将归属于来源):
我有两个名为tblBooking和tblRoom的表 tblBooking有一个ID,Day,RoomID;
tblRoom有一个ID,描述我需要创建一个查询,显示哪些房间没有使用 某些天,即1,2,3,4,5,6,7
我怎样才能使用联合查询?我尝试了所有不同的 组合,但无法得到任何工作,请帮助
答案 0 :(得分:2)
尝试使用用于创建日历表天:
的联合select Day, Room ID
from (
select Day=1 union select Day=2 union select Day=3 union select Day=4 union
select Day=5 union select Day=6 union select Day=7
) Days
cross join tblRoom
except
select Day, RoomID from tblBooking
order by RoomID, Day
答案 1 :(得分:2)
在SQL Server 2008+中,您还可以使用表值构造函数:
SELECT Day, RoomID
FROM (VALUES (1),(2),(3),(4),(5),(6),(7)) as Days(Day)
CROSS JOIN tblRoom
EXCEPT
SELECT Day, RoomID FROM tblBooking
ORDER BY RoomID, Day
http://www.sql-server-helper.com/sql-server-2008/row-value-constructor-as-derived-table.aspx http://msdn.microsoft.com/en-us/library/dd776382.aspx
答案 2 :(得分:1)
这是另一种不使用UNION
WITH NumberSequence
AS
(
SELECT 1 Number
UNION ALL
SELECT Number + 1 FROM NumberSequence WHERE Number < 7
)
SELECT a.*, b.*
FROM NumberSequence a
CROSS JOIN (SELECT DISTINCT RoomID FROM TableName) b
LEFT JOIN TableName c
ON c.Day = a.Number AND c.RoomID = b.RoomID
WHERE c.RoomID IS NULL
ORDER BY a.Number, c.RoomID, c.Day
OPTION (MaxRecursion 1000)