0

我有一张桌子,里面有一些时隙,例如:

#id datet           userid  agentid duration    
+=======================================================+
|1  |2013-08-20 08:00:00    |-1 |3  |5  
|2  |2013-08-20 08:05:00    |-1 |3  |5  
|3  |2013-08-20 08:10:00    | 3 |3  |5  
|4  |2013-08-20 08:15:00    |-1 |3  |5  
|5  |2013-08-20 08:20:00    |-1 |3  |5  
|6  |2013-08-20 08:25:00    |-1 |3  |5  
|7  |2013-08-20 08:30:00    |-1 |3  |5  
|8  |2013-08-20 08:05:00    |-1 |7  |15 
|9  |2013-08-20 08:20:00    |-1 |7  |15 
+=======================================================+

在上面的示例中,ID 为 3 的用户在 8:10 有一个时段。(如果 userid = -1,则表示它是一个空闲插槽)。他与代理 5 有约会。例如,现在用户 3 想要另一个时间段,但这次与代理 7。因此,算法应该只保留 agentid 7 的空闲时间段,并且可能的时间段不重叠。这意味着,在这种情况下,只有第 9 条记录是一个解决方案。(但也许在另一种情况下,有多种解决方案)。另一件事是,用户只能与同一个代理进行一次约会。

任何想法如何实现这一点?我在考虑 OVERLAPS 运算符,但不知道该怎么做。

4

1 回答 1

1

尝试类似:

select *
from  time_slots ts
where agentid = 7 -- or any agent
  and userid = -1 -- it is free
  and not exists (select 1 -- and overlaping interval does not exist
                 from time_slots ts_2
                 where ts_2.userid <> -1 -- not free
                   and (ts.datet, ts.datet + interval '1 hour' * ts.duration) OVERLAPS
                       (ts_2.datet, ts_2.datet + interval '1 hour' * ts_2.duration))
于 2013-08-21T15:13:36.240 回答