2015-06-06 54 views
2

我作爲如何將時間列的值劃分爲排在SQL Server 2008R2

|start    ||  end1   | 

1/06/2015 1:00  ||  1/06/2015 1:30 

1/06/2015 2:00  ||  1/06/2015 3:00 

1/06/2015 3:20  ||  1/06/2015 4:00 

1/06/2015 4:00  ||  NULL 

我想要的輸出表: -

|start   || end1   | 

1/06/2015 1:00 || 1/06/2015 1:30 

1/06/2015 1:30 || 1/06/2015 2:00 

1/06/2015 2:00 || 1/06/2015 3:00 

1/06/2015 3:00 || 1/06/2015 3:20 

1/06/2015 3:20 || 1/06/2015 4:00 

1/06/2015 4:00 || NULL 

我想下面所提到的代碼,但它沒有給我想要的輸出..

with cte as 
(select 
    start 
    ,end1 
    ,ROW_NUMBER() over (order by (select 1)) as rn 
from #b 
),cte1 as 
(select top 1 
    start 
    ,end1 
    ,rn 
from cte 
    union all 
    select 
    a.end1 
    ,(case when (b.rn) %2 = 0 then b.start else b.end1 end) 
    ,b.rn 
from cte1 as a 
    inner join cte as b 
    on b.rn = a.rn +1 

) 
select start,end1 
from cte1 

我得到錯誤的輸出 -

| start  ||  end1 | 

1/06/2015 1:00 || 1/06/2015 1:30 

1/06/2015 1:30 || 1/06/2015 2:00 

1/06/2015 2:00 || 1/06/2015 4:00 

1/06/2015 4:00 || 1/06/2015 4:00 

有人可以幫助我請我過去2小時以來,我沒有得到所需的輸出。

+0

什麼是您預期的輸出? – FutbolFan

+0

我已經在我的問題的底部提到了它,就在「我輸錯了錯誤」一行的下面。我試圖製作一張桌子,但我無法做到。我的輸出表有3列start,end1,rn。 – sam

+0

是的,如果您在問題中顯示錯誤的輸出,然後說'我沒有獲得所需的輸出結果,那麼這並沒有多大幫助。'如果您需要幫助,您需要更好地解釋它。 – FutbolFan

回答

1

滯後可能無法在SQL 2008,可嘗試此

declare @tb table ([start] datetime, end1 datetime) 
    insert into @tb ([start],end1) values(
    '1/06/2015 1:00','1/06/2015 1:30'), 
    ('1/06/2015 2:00','1/06/2015 3:00'), 
    ('1/06/2015 3:20','1/06/2015 4:00'), 
    ('1/06/2015 4:00',NULL) 


    ;with ct as(select start,row_number() over (order by start) as rno 
from (select [start] from @tb union select end1 from @tb) t 
where start is not null) 
    select start,end1 from ct t left join (select rno, start end1 from ct) t1 
on t.rno+1=t1.rno 
+0

偉大的工程就像一個魅力..謝謝..我在灌木叢中跳動以獲得解決方案。我嘗試了所有可能的方式但失敗了。你的解決方案非常簡單,很棒 – sam

0

你可以使用lead()功能來做到這一點:

;WITH cte1 
AS (
    SELECT start 
    FROM timeline --replace this with your tablename 

    UNION ALL 

    SELECT end1 start 
    FROM timeline --replace this with your tablename 
    ) 
    ,cte2 
AS (
    SELECT start 
     ,lead(start) OVER (
      ORDER BY start 
      ) end1 
    FROM cte1 
    ) 
SELECT * 
FROM cte2 
WHERE start <> coalesce(end1, '1900-01-01 00:00') 

Demo

+0

在sql server 2008中沒有Lead()函數的功能。它在2012年及以上 – sam

+0

你是對的!無論如何,這應該適用於在SQL Server 2012中尋找解決方案的任何人。 – FutbolFan

相關問題