我希望在2012年1月至2013年1月的日期范围内找到每月的员工人数。
示例历史:
我想要结果,
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 */
答案 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)