簡體   English   中英

SQL Server:計算先前日期和當前日期之間的天數差

[英]SQL Server: Count days difference between previous date and current date

我一直在嘗試找到一種方法來計算上一行和當前行的兩個日期之間的天差,后者僅計算工作日。

示例數據和標准在這里。

  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的情況)。
  • 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的上一行(ID 0)中的空值(打印出StartDate而不是EndDate),所以我對ID 2、3、4擁有正確的DaysDifference,因此它計數不正確。

希望我提供了足夠的信息。 :)

您能否指導我正確計算DaysDifference的方法。

提前致謝!

我認為您可以使用此邏輯來獲取以前的日期:

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM