我有一张桌子可以跟踪某人是否有人在他们开始工作时和他们完成工作时进行跟踪。我有一些代码可以计算在给定日期范围内表中发生的星期日数。
这是我的原始代码:
select empnum,
count(distinct dateadd(day, datediff(day, 0, starttime), 0)) as NumberOfSundays
from table
where (datename(dw, starttime) = 'Sunday')
group by empnum
现在我还需要在周六开始但周日结束时出现。但是,当我包含或声明包含这些额外的班次时,他们会额外计算。也就是说,如果有人在星期六工作并且在周日再次工作然后在星期日再次工作,那么当我只需要1时,我得到2的计数。
这是我的代码,我需要更改什么,以便星期六或星期日轮班只计为1:
select empnum,
count(distinct dateadd(day, datediff(day, 0, starttime), 0)) as NumberOfSundays
from table
where (datename(dw, starttime) = 'Sunday'
or (datename(dw, starttime) = 'Saturday' and datename(dw, endtime) = 'Sunday'))
group by empnum
答案 0 :(得分:0)
这样可行:
SELECT empnum,
count(DISTINCT dateadd(day, datediff(day, 0, starttime), 0)) AS NumberOfSundays
FROM TABLE
WHERE (
datename(dw, starttime) = 'Sunday'
OR (
datename(dw, starttime) = 'Saturday'
AND datename(dw, endtime) = 'Sunday'
AND empnum NOT IN (
SELECT empnum
FROM TABLE
WHERE datename(dw, starttime) = 'Sunday'
)
)
)
GROUP BY empnum