如何将时间列值拆分为sql server 2008R2中的行

时间:2015-06-06 14:38:22

标签: sql-server-2008

我的表格为

|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小时内尝试过,而且我没有得到所需的输出。

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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