-1

我有一个 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

4 回答 4

1

完成此操作的一种简单方法是创建一个日历表,其中将日期、星期几和一年中的日期全部加载到表中。然后,您只需选择自员工开始日期以来的天数,其中星期几!= 周六或周日。

于 2013-07-17T14:09:22.750 回答
1

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

于 2013-07-17T15:11:40.217 回答
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');

更简单的是,如果您创建一个仅包含 weekdays 的名为 "weekdays" 的视图。. .

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

这个 SO 答案有一个日历表的 PostgreSQL 代码。你可以很容易地为 SQL Server 调整它。

于 2013-07-17T15:15:04.527 回答
0

如果需要准确,
STEP01 减去 2 乘以数字整数(DATEDIFF RESULT)除以 7
STEP02 THEN 取 7 减去工作日(START DATE)数字(USE 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
于 2014-10-16T22:37:32.303 回答