根据日期范围计算天数

时间:2019-10-23 13:41:57

标签: sql sql-server sql-server-2016

我有如下数据

create table #Temp(Id int, FromDate date, ToDate date)
Insert into #Temp
values(1,'9/1/2019','9/1/2019'),
        (2,'9/2/2019','9/3/2019'),
        (3,'9/2/2019','9/3/2019'),
        (4,'9/4/2019','9/6/2019'),
        (5,'9/7/2019','9/7/2019')

我正在尝试计算差异并创建天数,即第1天,第2-3天等...

预期结果

Id  FromDate    ToDate      Display
1   01/09/2019  01/09/2019  Day 1
2   02/09/2019  03/09/2019  Day 2-3
3   02/09/2019  03/09/2019  Day 2-3
4   04/09/2019  06/09/2019  Day 4-6
5   07/09/2019  07/09/2019  Day 7

我尝试使用datediff尝试以下代码,但不确定如何与上一行相关并获取日期范围

select *, DATEDIFF(DAY,FromDate,ToDate)
from #Temp

3 个答案:

答案 0 :(得分:2)

使用first_value

select *
 , datediff(day, first_value(FromDate) over(order by FromDate), FromDate) + 1
 , datediff(day, first_value(FromDate) over(order by FromDate), ToDate) + 1
from #Temp

答案 1 :(得分:1)

如果您想要完全相同的输出,可以尝试一下

Select 
      * ,
     case 
      when (FromDate != ToDate) 
       then 
        'Day '+ DATEPART(Day,FromDate) + '-' + DATEPART(Day,ToDate)
       else
      'Day '+ DATEPART(Day,FromDate)
      END AS Display
    From #Temp

答案 2 :(得分:0)

您不想要上一行的值,您想要最早的fromdate,然后可以将其与每一行进行比较。

select id, min (fromdate) over (order by fromdate asc) as earliest_date,fromDate,todate,
datediff(day,min (fromdate) over (order by fromdate asc),fromdate)+1,
datediff(day,min (fromdate) over (order by fromdate asc),todate)+1
from
#temp

Fiddle