【问题标题】:Explain this code that calculates working days解释这段计算工作日的代码
【发布时间】:2014-04-17 20:49:34
【问题描述】:

我希望有人能帮助解释这段代码是如何工作的?

SELECT 
    dbo.Person.FullName, dbo.Person.Initials,
    (DATEDIFF(dd, @startdate, @enddate) + 1) -
       (DATEDIFF(wk, @startdate, @enddate) * 2) -
       (CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END) -
       (CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END) -
       (Select Count(*) FROM  [dbo].[W2BankHoliday] 
        Where [dbo].[W2BankHoliday].[bhDate] >= @StartDate AND [dbo].[W2BankHoliday].bhDate < @EndDate) AS WorkDays
FROM dbo.Person

【问题讨论】:

  • 不明白哪一部分?
  • +1 和 2 有什么作用?为什么要从包含银行假日日期的表中计数()?
  • 这段代码想为你解决什么问题?

标签: sql-server tsql formula


【解决方案1】:

这是该查询的每个部分的细分

SELECT 

    /* persons details */
    dbo.Person.FullName, dbo.Person.Initials,

    /* difference in days from start to end */
    (DATEDIFF(dd, @startdate, @enddate) + 1) - 


    /* difference in weeks times two (to allocate for weekends) */
    (DATEDIFF(wk, @startdate, @enddate) * 2) -

    /* discounting if started or finished on a weekend */
    (CASE WHEN DATEPART(dw, @startdate) = 1 THEN 1 ELSE 0 END) -
    (CASE WHEN DATEPART(dw, @enddate) = 7 THEN 1 ELSE 0 END) -

    /* discounting all bank holidays */
    (
        Select Count(*) FROM  [dbo].[W2BankHoliday] 
        Where [dbo].[W2BankHoliday].[bhDate] >= @StartDate 
        AND [dbo].[W2BankHoliday].bhDate < @EndDate
    ) AS WorkDays
FROM dbo.Person

现在这实际上意味着是

difference in days from start to end

minus

difference in weeks times two (to allocate for weekends)

minus

discounting if started or finished on a weekend

minus 

discounting all bank holidays

嗯,更好的解释是

Total days between beginning to end

minus

number of days for weekends

minus

number of days to be taken off if started or finished on weekend

minus 

number of bank holidays between start and finish date

我想你没有得到正确的答案。这可能是因为您在第一行执行 Start-end,而您应该执行 end-start。

【讨论】:

  • +1 和 2 有什么作用?为什么要从包含银行假日日期的表中计数()?
猜你喜欢
  • 1970-01-01
  • 2018-12-24
  • 2013-08-24
  • 2015-07-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多