従業員データベースに入社日と退職日が入ってるんだけど、そこから月別の在籍人数のレポートを作ったのでメモ。
なお、 DB は Snowflake である。
set from_date = date('2020-01-01');
set to_date = current_date();
with recursive month as (
select $from_date as count_date
union all
select dateadd(month, 1, count_date)
from month
where count_date < $to_date
)
,base as (
select e.user_id
,date_trunc(month, e.join_date) as count_date
,e.join_date
,e.last_date_worked
from dim_employee as e
where e.join_date < $to_date
order by e.join_date
)
select
b.user_id
,m.count_date
,b.join_date
,b.last_date_worked
,case
when m.count_date <= coalesce(b.last_date_worked, current_date())
then 1
else 0
end as count_employees
from month as m
inner join base as b on (m.count_date >= b.count_date)
order by m.count_date
set で変数宣言出来るので便利ね。
あと recursive で日付を生成出来るのも便利。
※あとで dim_date (日付ディメンション) テーブルを作るので一時的な対策。
この recursive CTE で生成した日付に対して、あとは dim_employee (従業員ディメンション) テーブルに社員の JOIN_DATE (入社日) と LASTE_DATE_WORKED (退職日) の日付を比較する。
これで毎月1日時点での fct_headcount_snapshot (在籍社員スナップショット) というファクトテーブル を作った。
さらにこれに対して、下記のクエリを実行してデータマートにしてあげれば完成。
select
count_date
,count(distinct user_id) as num_employee
from fct_headcount_snapshot
group by count_date
order by count_date