对于我所做的假定所有的例子,在BookedSchedules
的开始和结束时间会精确地匹配与StaffSchedules
开始和结束倍。
随着CTE,类似这样的问题:
我不推荐使用此查询,但它可能是有帮助的,因为它是类似问题的查询。它不太可读。
with NonBookingSlots as
(
select null as StaffId,StartdateTime,EndDateTime from Holidays
union all
select StaffId,StartdateTime,EndDateTime from BookedSchedules
)
select
StaffId, StartdateTime, EndDateTime
from
StaffSchedule
where
not exists(
select
1
from
NonBookingSlots
where
StaffSchedule.StaffId = isnull(NonBookingSlots.StaffId,StaffSchedule.StaffId)
and (
(
StaffSchedule.StartDateTime = NonBookingSlots.StartDateTime
and StaffSchedule.EndDateTime = NonBookingSlots.EndDateTime
) or (
StaffSchedule.StartDateTime < NonBookingSlots.EndDateTime
and StaffSchedule.EndDateTime > NonBookingSlots.StartDateTime
)
)
)
SQL小提琴:http://sqlfiddle.com/#!3/9cbf4/14
没有CTE:
这个版本是在我看来,更具有可读性。
select
StaffId, StartdateTime, EndDateTime
from
StaffSchedule
where
not exists(
select
1
from
BookedSchedules
where
StaffSchedule.StaffId = BookedSchedules.StaffId
and StaffSchedule.StartDateTime = BookedSchedules.StartDateTime
and StaffSchedule.EndDateTime = BookedSchedules.EndDateTime
) and not exists(
select
1
from
Holidays
where
StaffSchedule.StartDateTime < Holidays.EndDateTime
and StaffSchedule.EndDateTime > Holidays.StartDateTime
)
SQL小提琴:http://sqlfiddle.com/#!3/9cbf4/15
随着外键 - 我建议:
如果BookedSchedules
总是匹配StaffSchedule
你应该使用外键StaffSchedule
,而不是复制的开始并在BookedSchedules
结束时间。这会产生更清晰和更高效的查询。
select
StaffId, StartdateTime, EndDateTime
from
StaffSchedule
where
not exists(
select
1
from
BookedSchedules
where
StaffSchedule.Id = BookedSchedules.StaffScheduleId
) and not exists(
select
1
from
Holidays
where
StaffSchedule.StartDateTime <= Holidays.EndDateTime
and StaffSchedule.EndDateTime >= Holidays.StartDateTime
)
SQL小提琴:http://sqlfiddle.com/#!3/8a684/3
+1为一个完整的问题 – Kermit
能否在工作人员的安排被部分预订或者只客满(如与您的所有示例数据的情况下)? –
@ShWiVeL,其全套 – Billa