解释这个计算工作日的代码

时间:2014-04-17 20:49:34

标签: sql-server tsql formula

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

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 个答案:

答案 0 :(得分:0)

以下是该查询的每个部分的细分

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,而你应该做最后的开始。