2

I want number of working days in between to dates. For example if we have 01-01-2012 and 20-01-2012, i want to get the number of working days in between that two dates using T-SQL.

4

4 回答 4

7

由于 SQL Server 不知道您的公司认为工作日是多少,因此该问题的最佳答案可能是使用日历表。一旦你有一个包含过去和未来日期的表,并且列如IsWorkDay正确更新,查询很简单:

SELECT [Date] FROM dbo.Calendar 
  WHERE [Date] >= @start 
  AND [Date] <= @end
  AND IsWorkDay = 1;
于 2012-06-18T11:42:15.610 回答
3
DECLARE @fromDate datetime, @toDate datetime 
SELECT @fromDate = ' 01-01-2012', @toDate = '20-01-2012'

SELECT (DATEDIFF(day, @fromDate, @toDate) + 1) 
        - (DATEDIFF(week, @fromDate, @toDate) * 2)  
        - (CASE WHEN DATENAME(weekday, @fromDate) = 'Sunday' THEN 1 ELSE 0 END) 
        - (CASE WHEN DATENAME(weekday, @toDate) = 'Saturday' THEN 1 ELSE 0 END)
于 2012-06-18T11:56:51.067 回答
1

我喜欢 Aaron Bertrand 的建议,所以我编写了这段代码,可以添加到您的查询中。它在 2 个日期之间创建一个表变量,然后您可以通过加入 CalendarDate 列在查询中使用该变量(只需记住在加入之前删除任何时间信息)。这是基于周一到周五的典型美国工作周。

DECLARE @StartDate DATE
DECLARE @EndDate DATE

SET @StartDate = '2013-08-19'
SET @EndDate = '2013-08-26'

DECLARE @BusinessDay TABLE
(
    CalendarDate DATETIME,
    IsBusinessDay INT
)

DECLARE @Counter DATETIME = @StartDate
WHILE(@Counter <= @EndDate)
BEGIN
    INSERT INTO @WorkDays
    SELECT @Counter, CASE WHEN DATENAME(WEEKDAY, @Counter) NOT IN ('Saturday', 'Sunday') THEN 1 ELSE 0 END
    SET @Counter = DATEADD(DAY, 1, @Counter)
END

SELECT * FROM @BusinessDay

缺点是必须为每个需要它的查询重新创建它,因此如果您经常这样做,固定表可能是更好的方法。

可以这样使用......

SELECT 
     BusinessDays = SUM(IsBusinessDay)
FROM
     @BusinessDay
WHERE
     CalendarDate BETWEEN @StartDate AND @EndDate

这将为您提供两个日期之间的工作日数。就像许多其他人所说的那样,这显然没有考虑到任何假期或我的生日。

于 2013-08-20T19:56:59.837 回答
0

根据之前的代码,我对其进行了调整以排除最后一天(未询问但我需要它)。

    select (DATEDIFF(dd,@fromDate, @toDate))    
- (DATEDIFF(ww,@fromDate, DATEADD(dd,-1,@toDate)) * 2) 
- (CASE WHEN DATENAME(dw, @fromDate) = 'Sunday' THEN 1 else 0 end)
- (CASE WHEN DATENAME(dw, @toDate) = 'Sunday' THEN 1 else 0 end)

我使用包含这些日期的表格删除了圣日

   - ( select count(distinct dcsdte) 
    from calendar_table 
    where dcsdte between @fromDate 
        and @toDate )
于 2015-11-16T17:10:22.193 回答