SQL Server:在同一列的日期之间获取天数

时间:2017-09-08 00:44:08

标签: sql sql-server tsql

假设我有一张包含以下日期的表格:

2017-09-07
2017-09-07
2017-09-07
2017-09-07
2017-09-07
2017-09-07
2015-09-09
2014-09-13
2014-09-13
2014-09-13
2014-09-13
2012-09-11
2012-09-11
2012-09-07
2012-09-07

如何获取日期更改之间的天数差异(从更改日期起经过的天数)

我应该得到这个:

DATE        DAYSPASSED
----------------------
2017-09-07  729
2017-09-07  729
2017-09-07  729
2017-09-07  729
2017-09-07  729
2017-09-07  729
2015-09-09  361
2014-09-13  732
2014-09-13  732
2014-09-13  732
2014-09-13  732
2012-09-11    4
2012-09-11    4
2012-09-07    0
2012-09-07    0

2 个答案:

答案 0 :(得分:2)

也许是 CROSS APPLY

示例

Select A.*
      ,DaysPassed = IsNull(DateDiff(DAY,B.NxtValue,A.DateCol),0)
 From  YourTable A
 Cross Apply (Select NxtValue=max(DateCol) From @YourTable Where DateCol<A.DateCol) B
 Order By DateCol Desc

<强>返回

enter image description here

答案 1 :(得分:2)

declare @Table1 table
    ([dates] datetime)
;

INSERT INTO @Table1
    ([dates])
VALUES
    ('2017-09-07 00:00:00'),
    ('2017-09-07 00:00:00'),
    ('2017-09-07 00:00:00'),
    ('2017-09-07 00:00:00'),
    ('2017-09-07 00:00:00'),
    ('2017-09-07 00:00:00'),
    ('2015-09-09 00:00:00'),
    ('2014-09-13 00:00:00'),
    ('2014-09-13 00:00:00'),
    ('2014-09-13 00:00:00'),
    ('2014-09-13 00:00:00'),
    ('2012-09-11 00:00:00'),
    ('2012-09-11 00:00:00'),
    ('2012-09-07 00:00:00'),
    ('2012-09-07 00:00:00')
;
select a.dates, b.dayspassed from
@table1 a inner join ( 

select   dates, 
coalesce(datediff(day,LEAD (dates) OVER (order by  dates desc),dates),0) dayspassed

 from @table1  
  group by dates) b on a.dates=b.dates
  order by a.dates desc