我有一个场景,我希望根据日期和时间差异将我的日期列拆分为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
我希望我能让它变得可以理解。如果您需要更多说明,请告诉我。
答案 0 :(得分: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;
答案 1 :(得分: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
答案 2 :(得分: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
谢谢, 阿伦
答案 3 :(得分:1)
如果我理解正确,您希望将记录按顺序排列在一起。 这是问题的SQL小提琴:http://sqlfiddle.com/#!6/02afb/7
在cte排名日期让我们按顺序配对记录。
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