查询按月查找员工人数

时间:2014-02-18 11:58:56

标签: postgresql

我希望在2012年1月至2013年1月的日期范围内找到每月的员工人数。

示例历史:

  • 我们在2012年之前雇用了500名员工
  • 2012年1月 - 雇用了30名员工
  • 2月 - 20名员工离开公司 -March - 没有改变

我想要结果,

Jan 2012   530
Feb 2012   510
March 2012 550
...

employees表中,我有列:

id
employee_name
date_started
date_terminated
employee_status_type /* true for current employees, false otherwise */

1 个答案:

答案 0 :(得分:1)

create table employees (id int, date_started date, date_terminated date);

insert into employees values
  (1,'2012-01-01','2012-07-01'),
  (2,'2012-11-01',NULL),
  (3,'2010-01-01','2012-02-10');

with

time_space as (
  select
    gs::date as bom,
    (gs + interval '1 month' - interval '1 day')::date as eom
  from
     generate_series('2012-01-01'::date,'2013-01-01'::date, '1 month') gs

)

select
  ts.bom,
  coalesce(x.employees,0) as employees
from
  time_space ts
  left join (
    select
      bom,
      count(*) as employees
    from
      time_space ts
      join employees e on (coalesce(e.date_terminated,'3000-01-01'::date) >= ts.bom and e.date_started <= ts.eom)
    group by
      bom) x using (bom)

SQLFiddle