sql – 按日期计算的活动员工总数

我在过去的书面查询中给出了按日期计算的数据(雇用,终止等),如下所示:

SELECT per.date_start AS "Date",
  COUNT(peo.EMPLOYEE_NUMBER) AS "Hires"

FROM hr.per_all_people_f peo,
  hr.per_periods_of_service per

WHERE per.date_start BETWEEN peo.effective_start_date AND peo.EFFECTIVE_END_DATE

AND per.date_start BETWEEN :PerStart AND :PerEnd

AND per.person_id = peo.person_id

GROUP BY per.date_start

我现在想要按日期创建一个活跃员工的数量,但是我不确定如何约会查询,因为我使用范围确定活动如此:

SELECT COUNT(peo.EMPLOYEE_NUMBER) AS "CT"

FROM hr.per_all_people_f peo

WHERE peo.current_employee_flag = 'Y'

and TRUNC(sysdate) BETWEEN peo.effective_start_date AND peo.EFFECTIVE_END_DATE

最佳答案 这是一个简单的入门方法.这适用于数据中的所有有效日期和结束日期:

select thedate,
       SUM(num) over (order by thedate) as numActives
from ((select effective_start_date as thedate, 1 as num from hr.per_periods_of_service) union all
      (select effective_end_date as thedate, -1 as num from hr.per_periods_of_service)
     ) dates

它的工作原理是为每个开始添加一个人,并为每个末尾减去一个(通过num)并进行累积求和.这可能有重复的日期,因此您也可以进行聚合以消除这些重复项:

select thedate, max(numActives)
from (select thedate,
             SUM(num) over (order by thedate) as numActives
      from ((select effective_start_date as thedate, 1 as num from hr.per_periods_of_service) union all
            (select effective_end_date as thedate, -1 as num from hr.per_periods_of_service)
           ) dates
     ) t
group by thedate;

如果您真的想要所有日期,那么最好从日历表开始,并使用原始查询的简单变体:

select c.thedate, count(*) as NumActives
from calendar c left outer join
     hr.per_periods_of_service pos
     on c.thedate between pos.effective_start_date and pos.effective_end_date
group by c.thedate;
点赞