這是一個非常好的問題,回答很難。首先我等待別人來解決它,但由於沒有發生,我試了一下,發現了一個錯誤,並再次嘗試。
它不是很漂亮,但似乎沒有支持問題的SQL功能。所以SQL很複雜。如果有人提出了另一個更好的解決方案,我會首先給予它一個優點。
declare @t table (name varchar(10), rank int, start datetime, stop datetime, code varchar(12))
insert @t values ('Joey', 52, '2011-06-21 11:30', '2011-06-21 11:45', 'BRK_Break1')
insert @t values ('Joey', 53, '2011-06-21 17:30', '2011-06-21 17:45', 'BRK_Break2')
insert @t values ('Joey', 57, '2011-06-21 14:15', '2011-06-21 15:15', 'BRK_Lunch')
insert @t values ('Joey',152, '2011-06-21 09:40', '2011-06-21 19:00', 'CONT_Shift')
insert @t values ('Joey',152, '2011-06-22 09:40', '2011-06-22 19:00', 'CONT_Shift')
;with aa as
(
select name, rank, start, 'b' action, code from @t
union all
select name, rank, stop, 'e', code from @t
)
select * from (
select name,start,
(select min(start) from aa where start > a.start and a.name = name) stop,
(select code from (select rank() OVER (ORDER BY rank) as rank, code from @t where dateadd(second, 1, a.start) between start and stop and name = a.name) c where rank = 1) code
from aa a
where not exists (select 1 from @t where a.start between start and stop and a.rank > rank and a.name = name)
and exists (select 1 from @t where a.start between start and stop and a.name = name)
) d
where code is not null and
name = 'Joey'
order by start
你能以何種方式在時間線是基於「等級」解釋清楚,你可以通過簡單的工作了得到這些結果在開始和結束時間相交 –
如果有衝突的項目最低等級應該優先考慮。 E.G如果Cont_Shift等級爲1,我們永遠不會看到最終數據中的任何其他代碼,因爲Cont_shift是從9:40到19:00 –
可能的不同類型的範圍的數量是否固定? –