我们在ms sql server中有datediff()。 我希望在两天之间找到“工作”日(周日除外)。 例如如果我使用datediff(day,'2014-05-01','2014-05-31')那么它应该给出除星期日之外的日数
有没有办法做到这一点?
答案 0 :(得分:0)
试试这个!
declare @d1 datetime,@d2 datetime
set @d1='2014-05-04'
set @d2='2014-05-18'
SELECT
(DATEDIFF(dd, @d1, @d2) + 1)
-(DATEDIFF(wk, @d1, @d2))
-(CASE WHEN DATENAME(dw, @d2) = 'Sunday' THEN 1 ELSE 0 END) -- discard sundays
答案 1 :(得分:0)
我想这个可以正常工作:
SET DATEFIRST 1;
DECLARE @StartDate DATE = '2014-05-01',
@EndDate DATE = '2014-05-31';
DECLARE @RenamingDays INT = DATEDIFF(D,@StartDate,DATEADD(DAY,1,@EndDate)) % 7;
DECLARE @NoOfWeeks INT = DATEDIFF(D,@StartDate,DATEADD(DAY,1,@EndDate)) / 7;
;with cte as
(
SELECT @EndDate Dates,
0 i
WHERE @RenamingDays > 0
UNION ALL
SELECT DATEADD(DAY, -1, Dates),
i + 1
FROM CTE
WHERE i + 1 < @RenamingDays
)
,WorkingDays AS
(
SELECT COUNT(Dates) RenamingWorkingDays
FROM cte
WHERE DATEPART(dw, Dates) != 7
)
SELECT @NoOfWeeks * 6 + RenamingWorkingDays
FROM WorkingDays