0

日付と時刻の差に基づいて、SQL で日付列を 2 つの日付列に分割するシナリオがあります。例えば

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

これを試してみてください -

クエリ:

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 に答える
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 に答える