SQL Server:计算上一个日期和当前日期之间的天数差异

时间:2018-03-26 14:36:52

标签: sql sql-server

我一直试图找到一种方法来计算两个日期之间的天数差异,这两个日期只计算工作日的前一行和当前行。

此处的示例数据和标准。

  ID        StartDate       EndDate         NewDate        DaysDifference
 ========================================================================
  0         04/05/2017      null       
  1         12/06/2017     16/06/2017      12/06/2017         29
  2         03/07/2017     04/07/2017      16/06/2017         13
  3         07/07/2017     10/07/2017      04/07/2017         5
  4         12/07/2017     26/07/2017      10/07/2017         13     

我的最终目标是 我想要两个新专栏; NewDate和DayDifference。

  • NewDate列来自上一行的EndDate。正如您所看到的那样,例如,ID 2的NewDate是16/06/2017,它来自ID 1的EndDate。但是如果前一行的EndDate中的值为null,则使用其StartDate(ID 1 case)。
  • DaysDifference列仅计算EndDate和NewDate列之间的工作日。

这是我正在使用atm的脚本。

    select distinct
    c.ID
    ,c.EndDate
    ,isnull(p.EndDate,c.StartDate) as NewDate
    ,count(distinct cast(l.CalendarDate as date)) as DaysDifference

    from    
                (select *
                from table) c
                full join
                (select *
                from table) p
                on c.level = p.level
                and c.id-1 = p.id           

    left join Calendar l
    on (cast(l.CalendarDate as date) between cast(p.EndDate as date) and cast(c.EndDate as date)
    or 
    cast(l.CalendarDate as date) between cast(p.EndDate as date) and cast(c.StartDate as date))
    and l.Day not in ('Sat','Sun') and l.Holiday <> 'Y'

    where c.ID <> 0 
    group by 
    c.ID
    ,c.EndDate
    ,isnull(p.EndDate,c.StartDate)

这是目前的结果:

  ID        EndDate         NewDate        DaysDifference
 =========================================================
  1         16/06/2017      12/06/2017         0
  2         04/07/2017      16/06/2017         13
  3         10/07/2017      04/07/2017         5
  4         26/07/2017      10/07/2017         13

在真实数据中看起来,除了ID 1之外,我还得到ID 2,3,4的正确DaysDifference,因为它的前一行(ID 0)的空值打印StartDate而不是null EndDate,所以它计算错误。

希望我已经提供了足够的信息。 :)

请您指导一下正确计算DaysDifference的方法。

提前致谢!

1 个答案:

答案 0 :(得分:0)

我认为您可以使用此逻辑来获取上一个日期:

select t.*,
       lag(coalesce(enddate, startdate), 1) over (order by 1) as newdate 
from t;

然后是差异:

select id, enddate, newdate,
       sum(case when c.day not in ('Sat', 'Sun') and c.holiday <> 'Y' then 1 else 0 end) as diff
from (select t.*,
             lag(coalesce(enddate, startdate), 1) over (order by 1) as newdate 
      from t
     ) t join
     calendar c
     on c.calendardate >= newdate and c.calendardate <= startdate
group by select id, enddate, newdate;