0

我有一个场景,我想根据日期和时间差异将我的日期列拆分为 SQL 中的两个日期列。例如

I have a date column with date and time.

       Date
2011-12-31 15:10:00
2011-12-31 19:20:00
2011-12-31 20:33:00

Now i want to split it like.

     From Date                To Date
2011-12-31 15:10:00     2011-12-31 19:20:00
2011-12-31 19:20:00     2011-12-31 20:33:00

等等....

另外,如果有任何日期差异,我想再次拆分,例如;

     From Date                To Date
2011-12-31 15:10:00     2012-1-30 19:20:00
2011-1-30 19:20:00      2012-2-28 20:33:00    

我希望我让它可以理解。如果您需要更多说明,请告诉我。

4

4 回答 4

4

这是你想要的?

WITH numbered AS(
  SELECT [Date], ROW_NUMBER()OVER(ORDER BY [Date]) rn
  FROM dbo.YourTable
)
SELECT [From].Date AS [From Date], [To].Date AS [To Date]
FROM numbered AS [From]
JOIN numbered AS [To]
ON [From].rn + 1 = [To].rn
ORDER BY [From].Date;
于 2013-05-08T09:37:09.933 回答
1

如果我理解正确,您想按照记录的顺序将记录配对。这是解决该问题的 SQL 小提琴:http ://sqlfiddle.com/#!6/02afb/7

cte 中的 rn 排名日期让我们按顺序配对记录。

WITH rankedDates as 
(
 SELECT
  id_Date
  ,ROW_NUMBER() over (order by id_Date)  as rn
  FROM test
)
SELECT
startd.id_Date as startDateTime
,endd.id_Date as endDateTime
FROM rankedDates as startd
INNER JOIN rankedDates as endd
  ON startd.rn +1 = endd.rn
于 2013-05-08T09:51:35.977 回答
1
 You can try that using looping through the column , might not be perfect answer you look need to insert the result into a temp but this logic might work , the advantage is that you have have any other logic in to this code 

if object_id('tempdb..#Temp','u') is not  null
    Drop table #Temp
    Create Table #Temp
    (
    sno int identity(1,1),
    datevalue datetime 
    )

    insert into #temp values ('2011-12-31 15:10:00'),
            ('2011-12-31 19:20:00'),
            ('2011-12-31 20:33:00')
     Select * from #temp
     DEclare @loop int=1, @column1   datetime,@column2 datetime
     While (@loop<=(select max(sno) from #temp))
     Begin
           Select @column1 =(select datevalue from #temp where sno=@loop) ,@column2=(select datevalue from #temp where sno=@loop+1)
           Select @column1,@column2
    set @loop=@loop+1

     End

谢谢,阿伦

于 2013-05-08T09:44:42.163 回答
1

试试这个——

询问:

DECLARE @temp TABLE
(
      col DATETIME
)

INSERT INTO @temp (col)
VALUES 
    ('2011-12-31 15:10:00'),
    ('2011-12-31 19:20:00'),
    ('2011-12-31 20:33:00')

SELECT * 
FROM @temp t
OUTER APPLY (
    SELECT TOP 1 t2.col
    FROM @temp t2
    WHERE t2.col > t.col
    ORDER BY t2.col
) t2
WHERE t2.col IS NOT NULL

;WITH cte AS
(
  SELECT col, ROW_NUMBER() OVER(ORDER BY col) rn
  FROM @temp
)
SELECT f.col, t.col
FROM cte f
JOIN cte t ON f.rn + 1 = t.rn

输出:

col                     col
----------------------- -----------------------
2011-12-31 15:10:00.000 2011-12-31 19:20:00.000
2011-12-31 19:20:00.000 2011-12-31 20:33:00.000
于 2013-05-08T09:38:28.460 回答