员工人数

时间:2019-03-16 15:39:05

标签: sql oracle

即使该年没有员工加入,我也必须按年份计算员工人数: 例如

emp_id start_dt term dt 
----------
1      1/1/2010  
----------
2      1/1/2011 12/31/2011
----------
3      1/1/2013
----------
4      1/1/2015 12/31/2016
----------
5      1/1/2016 
----------

我需要从发生首次冷杉到sysdate的每一年打印雇员人数。

2010 1
----------
2011 2
----------
2012 1
----------
2013 2
----------
2014 2
----------
2015 3
----------
2016 4
----------
2017 3
----------
2018 3
----------
2019 3

2 个答案:

答案 0 :(得分:2)

一种方法是从具有所有年份的表开始。然后,您可以计算当年在职员工的数量。

例如,

select y.year,
       (select count(*)
        from t
        where year(t.startdt) <= y.year and
              (year(t.termdt) >= y.year or t.termdt is null)
from (select 2011 as year union all
      select 2012 as year union all
      . . .  -- continue for the years of interest
     ) y;

这使用year()函数,该函数不是标准函数,但在许多数据库中都可用。官方功能为extract(year from startdt)

在Oracle中,您可以表示为:

select y.year,
       (select count(*)
        from t
        where extract(year from t.startdt) <= y.year and
              (extract(year from t.termdt) >= y.year or t.termdt is null)
from (select 2011 as year from dual union all
      select 2012 as year from dual union all
      . . .  -- continue for the years of interest
     ) y;

答案 1 :(得分:0)

这将起作用:

select  EXTRACT(YEAR FROM HIREDATE),count(*) from scott.emp group by EXTRACT(YEAR FROM 
HIREDATE);

对于您的案例查询将是:

select  EXTRACT(YEAR FROM START_DT ),count(*) from tablename group by EXTRACT(YEAR FROM 
START_DT );