Sql 在灵活范围内统计事件

Sql 在灵活范围内统计事件,sql,teradata,Sql,Teradata,我试图统计每个人在特定目标日期前一年和后一年的event_表中的行。例如,假设我有一个人100,目标日期是2012年1月10日。我想统计2011年9月30日至2012年9月30日和2012年2月10日至2013年9月30日的事件 我的查询如下所示: select * from ( select id, target_date from subsample_table ) as i left join ( select id, event_date, count(*

我试图统计每个人在特定目标日期前一年和后一年的event_表中的行。例如,假设我有一个人100,目标日期是2012年1月10日。我想统计2011年9月30日至2012年9月30日和2012年2月10日至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天以外的事情


如果您有任何建议,我们将不胜感激。

这是一个通用的答案。我不知道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可以有多个目标日期。

我认为以下内容可能接近您想要实现的目标

   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

不确定,但我不认为事件日期应该在选择列表中。虽然这是OP的问题,但也不确定时段是否应该在分组列表中+1尽管如此,我可能还是有点接近OP的例子。但是你可能是对的,鲍勃。感谢鹰眼。@DimitriyV.Masterov如果你认为回答了你的问题,记得接受回答。