选择不在时间范围内的表中的值



我有两个表(简化版):

create table Schedule(
Id int,
ScheduledData datetime,
UserId int)
create table User(
Id int,
Name varchar(50))

在第一个表中,我存储了所有预定的会议,并将其链接到一个用户。

我想要的是检索用户所有的空闲时间。不必写得很详细。

例如,如果用户没有将会议安排在07/02/2014上午(早于12:59:59),则显示包含用户姓名和日期的一行。如果他下午有空,也一样。

到目前为止,我所尝试的并没有工作是创建一个临时表,并在我的DB中填充每个月的所有日子和所有用户。使用CTE时效果很好:

create table #Temp(
StartData datetime,
EndDate datetim,
UserId int)

然后,我这样做来显示行:

select U.Name, X.ScheduledDate
from #Temp T
left outer join 
(select S.UserId
from Schedules S
where ScheduledData between @X and @Y) X on T.UserId = S.UserId
left outer join User U on T.UserId = U.Id
where S.ScheduledDate between T.StartDate and T.EndDate

它不能很好地工作,我不能理解它。我已经纠结了一整天了,这是目前为止我得到的最好的。

这个问题可能需要更详细的说明:

  • 'Schedule'中的一行是什么意思?' scheduledata '列只是时间上的一个瞬间;这是会议开始的时间吗?会议持续多长时间?
  • 显示"所有用户的空闲时间"是什么意思?时间是一个连续的(嗯,某种程度上)量。结果应该如何表示?

你的例子的精神似乎是,给定一段时间,对于会议是否在该时间内发生返回一个true/false值。假设您有一个名为"Users"的表,其中包含每个用户的ID。如何创建一个表'time_segments'与三列'id', 'start_time'和'end_time';你可以定义任何你想要的时间段,例如你的"早晨"块,然后获取空闲时间,如:

select UserId,all_slots.id
from
( select
    TimeSegments.id, UserId
  from
    TimeSegments
    cross join Users ) all_slots
left outer join
( select
    TimeSegments.id, UserId
  from
    Schedule
    cross join TimeSegments
  where
    Schedule.datetime between TimeSegments.start_time and TimeSegments.end_time
) booked using(id, UserId)
where
  booked.UserID is null

最新更新