比较SQL Server中下一个最小日期的两列中的日期

时间:2016-09-07 01:52:36

标签: sql-server tsql sql-server-2012

我有两个日期列Date1Date2。我想创建新列:

  • 新列NewDate1:使用Date1 '1994-03-31 00:00:00'中的第一行大于Date2中的该值并获取下一个最小值

  • 新专栏NewDate2:使用Date2 '1995-01-12 00:00:00'中的第一行大于Date1中的该值并获取下一个最小值。

    < / LI>

示例数据:

Date1                       Date2
---------------------       ---------------------
'1994-03-31 00:00:00'       '1995-01-12 00:00:00'
'1994-03-31 19:27:00'       '1995-04-13 00:00:00'
'1995-01-12 00:00:00'       '1995-04-13 09:29:00'
'1995-04-13 00:00:00'       '1997-01-12 09:59:00'
'1995-04-13 09:29:00'       '1999-07-19 00:00:00'
'2008-04-04 00:00:00'       '2009-08-06 00:00:00'
'2011-11-04 00:00:00'       '2013-04-01 00:00:00'
'2013-04-01 00:00:00'       NULL

我想这样:

NewDate1                    NewDate2
---------------------       ---------------------
'1994-03-31 00:00:00'       '1995-01-12 00:00:00'
'1995-01-12 00:00:00'       '1995-04-13 00:00:00'
'1995-04-13 00:00:00'       '1995-04-13 09:29:00'
'1995-04-13 09:29:00'       '1997-01-12 09:59:00'
'2008-04-04 00:00:00'       '2009-06-22 00:00:00'
'2011-11-04 00:00:00'       '2013-04-01 00:00:00'
'2013-04-01 00:00:00'       NULL

提前致谢

2 个答案:

答案 0 :(得分:1)

此查询将为您提供2个日期字段之间的所有时间段。如果这是您正在寻找的内容,请重定向到表格中。

;with AllDates as (
select Date1 as DateField from Table1
    union
    select Date2 as DateField from Table1
)
select d1.DateField, min( d2.DateField ) as NextDate
from AllDates d1
join AllDates d2
    on d1.DateField < d2.DateField
group by d1.DateField
union 
select max(DateField), null from AllDates

答案 1 :(得分:0)

你的问题究竟是什么?您是否想要将Date1和Date2列的值插入NewDate1和NewDate2列?

如果是,那么:

INSERT INTO DESTINATION_TABLE(NewDate1, NewDate2)
SELECT Date1, Date2 FROM WHATEVER_TABLE

这应该解决还是我误解了?