SQL Server查询在每月的15号获得X的计数

史蒂文·戴姆(Steven Deam)

我想创建一个SQL查询,该查询获取最近5年的每个月15日的受雇雇员数。

这个查询让我有一个月的时间:

SELECT
    SUM(X.CountOfEmployees)
FROM (SELECT
    COUNT(CNCEmployeeID) AS CountOfEmployees
FROM dbo.CNCEmployees
GROUP BY CNCEmployeeStartDate,
         CNCEmployeeDateLeft
HAVING (CNCEmployeeStartDate < CONVERT(datetime, '2016-07-15 00:00:00', 102))
AND ((CNCEmployeeDateLeft > CONVERT(datetime, '2016-07-15 00:00:00', 102))
OR (CNCEmployeeDateLeft IS NULL))) AS X

我在寻找什么会输出:

Jan 2016 - 32
Feb 2016 - 33
Mar 2016 - 33

等等,我们每个月都有数据。

我知道如何创建查询,至少可以通过添加变量并一遍又一遍地更改来快速手动更改日期(实际上,我可能会这样做,以便在过去12个月中完成今天的报告)。我认为,有一个更好的方法可以一步完成此操作,而无需每月手动进行。

戈登·利诺夫(Gordon Linoff)

一种方法可生成60个月,并将其用于join

with dates as (
      select cast(dateadd(day, 16 - day(getdate()), getdate()) as date) as thedate, 1 as num
      union all
      select dateadd(month, -1, thedate), num + 1
      from dates
      where num <= 60
     )
select d.thedate, count(e.CNCEmployeeStartDate)
from dates d left join
     dbo.CNCEmployees e
     on e.CNCEmployeeStartDate <= d.thedate and
        (e.CNCEmployeeDateLeft >= d.thedate or e.CNCEmployeeDateLeft is null)
group by d.thedate;

这不是最有效的方法,但是如果您有几百或几千名员工,那么就性能而言应该没问题。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章