2014-02-18 129 views
1

我想找到的員工數量在該日期範圍每個月找員工人數 - 2012年1月至2013年一月查詢每月

實例歷史:

  • 我們500名員工僱用前2012
  • 2012年1月 - 30名員工被錄用
  • 日 - 20名員工離開公司 -3月 - 什麼都沒有改變

我想導致像,

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
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