对于所有示例,我都假设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