我正在尝试计算每个人在特定目标日期之前和之后的年份中的事件(在event_table中的行)。例如,假设我有一个人100,目标日期是10/01/2012。我想计算9/30 / 2011-9 / 30/2012和10/02 / 2012-9 / 30/2013的活动。
我的查询如下:
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天以外的事件。
任何建议都将不胜感激。
答案 0 :(得分:2)
我认为以下内容可能接近您要完成的任务。
select id
, target_date
, event_date
, count(*) as N
, SUM(case when event_date between target_date-365 and target_date-1
then 1
else 0
end) AS Prior_
, SUM(case when event_date between target_date+1 and target_date+365
then 1
else 0
end) as After_
from subsample_table i
left join
event_table h
on i.id = h.id
and i.target_date = h.event_date
group by id, target_date, period
答案 1 :(得分:0)
这是一个通用的答案。我不知道teradata有什么日期函数,所以我将使用sql server语法。
select id, target_date, sum(before) before, sum(after) after, sum(righton) righton
from yourtable t
join (
select id, target_date td
, case when yourdate >= dateadd(year, -1, target_date)
and yourdate < target_date then 1 else 0 end before
, case when yourdate <= dateadd(year, 1, target_date)
and yourdate > target_date then 1 else 0 end after
, case when yourdate = target_date then 1 else 0 end righton
from yourtable
where whatever
group by id, target_date) sq on t.id = sq.id and target_date = dt
where whatever
group by id, target_date
这个答案假设一个id可以有多个目标日期。