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

时间:2016-09-01 21:05:20

标签: sql sql-server

我想创建一个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个个月)。我相信有一个更好的方法可以一步完成,而无需每个月手动完成。

1 个答案:

答案 0 :(得分:1)

一种方法生成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;

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