Tuesday, December 17, 2013

Get working days/weekday count

To get the number of weekdays/ working day (exclude Saturday and Sunday) between 2 dates.

Query
DECLARE @startdate DATETIME = '20130501', @enddate DATETIME = '20130531'

;WITH CTE AS(
      SELECT      @startdate AS Dates
      UNION ALL
      SELECT      Dates + 1
      FROM  CTE
      WHERE Dates < @enddate
)
SELECT
      [Date Column] = Dates,
      [English name of the day] = DATENAME(dw, Dates),
      [Formula] = DATEDIFF(DAY, 0, Dates)%7
FROM  CTE


As you can refer, the [Formula] column close together with [English name of the day]. We can easily filter Saturday and Sunday from the query by apply (WHERE DATENAME(dw, Dates) NOT IN ('Saturday', 'Sunday')). However, what if the server are supporting multi-languages? Something like below.

To solve this issue, the [Formula] came in place to solve the issue. By apply (WHERE DATEDIFF(DAY, 0, Dates)%7 < 5), weekends (Saturday and Sunday) are filtered, disregard the database languages.

No comments:

Post a Comment