如何计算不包括周末的总天数?

时间:2013-07-17 14:02:22

标签: sql sql-server

我有一个SQL查询,根据雇用日期(周年纪念日)计算员工工作的天数。但是,这些天包括周末,所以我需要排除星期六和星期日。我尝试使用DATEADD(dw, ...),但它没有用。

SELECT PRCo, Employee,LastName, FirstName, MidName,SSN,HireDate,
(case when 
      DATEADD(year, datediff(year, HireDate, getdate()), HireDate) < GETDATE()
 then DATEDIFF(dd, DATEADD(year, datediff(year, HireDate, getdate()), HireDate), getdate())
 else DATEDIFF(dd, DATEADD(year, datediff(year, HireDate, getdate()) - 1, HireDate),
               getdate()) end) as HRSDATE
FROM dbo.PREH

4 个答案:

答案 0 :(得分:1)

实现此目的的一种简单方法是创建一个日历表,其中日期,星期几和日期都加载到表中。然后,您只需选择员工开始日期的日期,即星期几!=星期六或星期日。

答案 1 :(得分:1)

只是从结果中减去2 * number of weeks

答案 2 :(得分:0)

使用合适的日历表,你可能会写这样的东西。 (假设雇用日期是2011-01-15。)日历表的一大优势是可以看到代码显然正确。

select count(*) as num_weekdays
from calendar
where cal_date between '2011-01-15' and current_date
  and day_of_week not in ('Sat', 'Sun');

更简单,如果您创建一个名为“工作日”但仅包含工作日的视图。 。

select count(*) as num_weekdays
from weekdays
where cal_date between '2011-01-15' and current_date;

This SO answer具有日历表的PostgreSQL代码。您可以非常轻松地为SQL Server调整它。

答案 3 :(得分:0)

如果它需要准确,
STEP01减去2倍数整数(DATEDIFF RESULT)除以7
步骤02然后取7减去工作日(开始日期)编号(使用DATEPART)
STEP03如果它大于数字(DATEDIFF RESULT),则减去2.

DECLARE @start AS datetime = '10/24/2014'

DECLARE @end AS datetime = '10/31/2014'
SELECT CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS int)AS STEP_ONE_OrigDays
--,CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money)*(1.000*(5.000/7.000)) AS EstDays
,(2.000*(CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money)/7)) AS STEP_TWO--SUBTRACT 2 times the number integer divided by 7
,DATEPART(dw, @start) AS STEP_THREE_WEEK_DAY_NUMBER --WEEK DAY #
,7 - DATEPART(dw, @start) AS STEP_FOUR_SEVENminus_WEEK_DAY_NUMBER --7 minus WEEK DAY #
,CAST(CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money)
-(2.000*(CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money)/7))
+CASE 
WHEN (7.000-DATEPART(dw, @start)) > CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money) 
THEN -2.000
ELSE 0.000 
END AS int) AS ExactDays_NOT_IncludingDayOf --JAH EXCLUDE WEEKEND Fx NOT Including the Day of
,CAST(CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money)-(2.000*(CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money)/7))
+CASE 
WHEN (7.000-DATEPART(dw, @start)) > CAST(DATEDIFF("d",CAST(@start AS datetime),CAST(@end AS datetime)) AS money) 
THEN -2.000
ELSE 0.000 
END AS int)+1 AS ExactDays_IncludingDayOf --JAH EXCLUDE WEEKEND Fx INCLUDING the Day of