SQL 不在(select 语句)之间的日期

SQL Date that is NOT between (select statement)

我不确定如何解决我遇到的这个问题。这就是我想要做的:

我有一个包含日历的 table,所以一年中的每一天 (yyyy-mm-dd)。

我还有另一个 table,其中包含我们设备工作的所有天数。此 table 是从我网站的另一部分填充的,但格式也是相同的 (yyyy-mm-dd)。

我有第三个 table,其中包含我们调度系统中的所有事件。通过这个系统,我们的员工可以预订我们的设备等的休息日。

所以我想做的是在日历中找到某个单位没有工作的所有休息日:

select *
from Calendar
where PKDate not in (select DayWorked
                from DaysWorked
                where Unit='105')

但我还需要考虑到设备的休息日。我不想将这些天包括在我的结果集中。这是活动(休息日)时间表的架构:

ID  | Name        | EventStart  | EventEnd    | UnitID
1     Days Off      2015-2-10     2015-2-15     105
2     Days Off      2015-3-2      2015-3-10     105

所有日期列都是 DateTime

我不知道如何在 SQL 查询的 NOT IN 子句中使用 EventStartEvetnEnd 列。我正在使用 SQL Server 2012。有什么想法吗?

我会使用 LEFT JOIN 来排除休息日的所有时间间隔 table:

SELECT Calendar.*
FROM
  Calendar LEFT JOIN DaysOff
  ON Calendar.PKDate BETWEEN DaysOff.EventStart AND DaysOff.EventEnd
     AND UnitID='105'
WHERE
  DaysOFf.ID IS NULL
  AND PKDate NOT IN (SELECT DayWorked
                     FROM DaysWorked
                     WHERE Unit='105')

NOT EXISTS 是我想到的:

select c.*
from calendar c
where not exists (select 1
                  from DaysWorked
                  where Unit = '105' and c.PKDate = d.DayWorked
                 ) and
      not exists (select 1
                  from DaysOff d
                  where Unit = '105' and
                        c.PKDate >= d.eventstart and c.PKDate <= d.eventend
                 );

注意:如果表中存储的日期极有可能包含时间部分,那么您需要调整查询以将其考虑在内。如果它们没有时间分量,您应该使用 date 而不是 datetime