各人の特定の目標日の前年と翌年のイベント(event_tableの行)をカウントしようとしています。たとえば、人が100人いて、目標日が2012年10月1日であるとします。2011年9月30日から2012年9月30日までと2012年10月2日から2013年9月30日までのイベントをカウントしたいと思います。
私のクエリは次のようになります。
select *
from (
select id, target_date
from subsample_table
) as i
left join (
select id, event_date, count(*) as N
, case when event_date between target_date-365 and target_date-1 then 0
when event_date between target_date+1 and target_date+365 then 1
else 2 end as after
from event_table
group by id, target_date, period
) as h
on i.id = h.id
and i.target_date = h.event_date
出力は次のようになります。
id target_date after N
100 10/01/2012 0 1000
100 10/01/2012 1 0
期間の前後(または両方)にイベントが発生しない人もいる可能性があります。その場合はゼロを設定すると便利です。730日以外のイベントは気にしません。
任意の提案をいただければ幸いです。