1

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 considered as current date.

This query does the job. But I do not want to count Sat and Sundays. Possible public UK Holidays.(I can do this one, if I can get the logic for Saturdays and Sundays)

SELECT  DateDiff(day,DateADD(day,-1,StartDate),ISNULL(EndDate,getDate()))numberOfDays
        FROM <mytable>

How do I count only weekdays between two dates?

Thank you

Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
Hari Gillala
  • 11,736
  • 18
  • 70
  • 117
  • possible duplicate of [Count work days between two dates in T-SQL](http://stackoverflow.com/questions/252519/count-work-days-between-two-dates-in-t-sql) – Mikael Eriksson Sep 16 '11 at 12:47

3 Answers3

4

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 ...

Community
  • 1
  • 1
Aaron Bertrand
  • 272,866
  • 37
  • 466
  • 490
2

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").

Christian Specht
  • 35,843
  • 15
  • 128
  • 182
1

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> 
Gunarathinam
  • 436
  • 1
  • 5
  • 14