Home > Database > Mysql Tutorial > How to Calculate the Number of Workdays Between Two Dates in SQL Server?

How to Calculate the Number of Workdays Between Two Dates in SQL Server?

Susan Sarandon
Release: 2025-01-21 23:21:17
Original
400 people have browsed it

How to Calculate the Number of Workdays Between Two Dates in SQL Server?

Calculating Business Days Between Dates in SQL Server

Efficiently determining the number of business days (Monday-Friday) between two dates is crucial for many SQL Server applications. This can be accomplished using a concise T-SQL expression. The following formula assumes a standard Monday-Friday work week:

<code class="language-sql">SELECT
    (DATEDIFF(day, @StartDate, @EndDate) + 1)
    - (DATEDIFF(week, @StartDate, @EndDate) * 2)
    - CASE WHEN DATENAME(weekday, @StartDate) = 'Sunday' THEN 1 ELSE 0 END
    - CASE WHEN DATENAME(weekday, @EndDate) = 'Saturday' THEN 1 ELSE 0 END</code>
Copy after login

Here, @StartDate and @EndDate represent the start and end dates. The calculation first finds the total number of days, then subtracts weekend days. It also handles edge cases where the start date is a Sunday or the end date is a Saturday.

For instance, with @StartDate = '2008/10/01' and @EndDate = '2008/10/31', the expression yields:

<code>(DATEDIFF(day, '2008/10/01', '2008/10/31') + 1)
- (DATEDIFF(week, '2008/10/01', '2008/10/31') * 2)
- CASE WHEN DATENAME(weekday, '2008/10/01') = 'Sunday' THEN 1 ELSE 0 END
- CASE WHEN DATENAME(weekday, '2008/10/31') = 'Saturday' THEN 1 ELSE 0 END</code>
Copy after login

This results in 21, representing the 21 business days between the given dates.

Remember: This calculation doesn't account for public holidays. For a more comprehensive solution including holidays, a more sophisticated query involving a holiday table would be necessary.

The above is the detailed content of How to Calculate the Number of Workdays Between Two Dates in SQL Server?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template