2011-06-21 21 views
3

我有以下如何打開時間排名的數據變成了「時間線」與T-SQL

 Agent Rank START STOP CODE 
     Joey 52  11:30 11:45 BRK_Break1 
     Joey 53  17:30 17:45 BRK_Break2 
     Joey 57  14:15 15:15 BRK_Lunch 
     Joey 152  09:40 19:00 CONT_Shift 

一組數據,它是一個人的「地位」在整個數據。該邏輯必須有對於每個時間「期間」一行因此它創建基於秩(低級=更高的優先級)一個contiunal「時間線」,因此它看起來像下面

Agent Start Stop Code 
Joey 09:40 11:30 CONT_Shift 
Joey 11:30 11:45 BRK_Break1 
Joey 11:45 14:15 CONT_Shift 
Joey 14:15 15:15 BRK_Lunch 
Joey 15:15 17:30 CONT_Shift 
Joey 17:30 17:45 BRK_Break2 
Joey 17:45 19:00 CONT_Shift 

任何想法如何這可以達到?理想情況下,我想限制登臺表的使用,並通過CTE或者一些自聯接來完成,但不確定從哪裏開始?

+0

你能以何種方式在時間線是基於「等級」解釋清楚,你可以通過簡單的工作了得到這些結果在開始和結束時間相交 –

+0

如果有衝突的項目最低等級應該優先考慮。 E.G如果Cont_Shift等級爲1,我們永遠不會看到最終數據中的任何其他代碼,因爲Cont_shift是從9:40到19:00 –

+0

可能的不同類型的範圍的數量是否固定? –

回答

2

這是一個非常好的問題,回答很難。首先我等待別人來解決它,但由於沒有發生,我試了一下,發現了一個錯誤,並再次嘗試。

它不是很漂亮,但似乎沒有支持問題的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 
+0

有趣。 +1,儘管它看起來很強大。我認爲可能有一個使用遞歸CTE的替代方案。當我有時間時,我希望儘快找到一個。 –

+0

這個效果很好,在使用之前需要充分理解它。將討厭拖放 –

+0

什麼是錯誤(我看你已經改變了代碼slighly)我使用以前的代碼,它似乎工作正常,除非我失去了一些東西? –