Business Days calculation

前端 未结 3 1154
悲哀的现实
悲哀的现实 2020-12-22 01:11

I have a query where I am calculating total days between two days including start and end date by the following SQL query. If the end date is not null, then end date is cons

相关标签:
3条回答
  • 2020-12-22 01:54

    I would strongly recommend a calendar table for this, especially if you need to take specific holidays into account. Calculating Easter dynamically, for example, is going to be a royal pain.

    http://web.archive.org/web/20070611150639/http://sqlserver2000.databases.aspfaq.com/why-should-i-consider-using-an-auxiliary-calendar-table.html

    If you're going to use T-SQL alone, be careful about using functions that rely on regional/language settings for the output of things like DATENAME ...

    0 讨论(0)
  • 2020-12-22 01:59

    Take a look at the DATEDIFF MSDN page. At the bottom of the page, there is some user-generated content.
    One user posted a function there which does exactly what you want, including holidays (headline: "UDF to return the number of business days, including a check to a bank holidays table").

    0 讨论(0)
  • 2020-12-22 02:12

    try this

    SELECT  DateDiff(day,DateADD(day,-1,StartDate),ISNULL(EndDate,getDate())) - 
    ( CASE WHEN DATENAME(dw, StartDate) = 'Sunday' OR 
    DATENAME(dw,ISNULL(EndDate,getDate())) = 'Sunday' THEN 1 ELSE 0 END)
    - ( CASE WHEN DATENAME(dw, StartDate) = 'Saturday' OR 
         DATENAME(dw,ISNULL(EndDate,getDate())) = 'Saturday' THEN 1 ELSE 0 END)
    numberOfDays         
    FROM <mytable> 
    
    0 讨论(0)
提交回复
热议问题