2017-04-15 92 views
0

使用tsql,我試圖找到一個成員是否在30天窗口內有三個單獨桶中的每個桶。桶不一定擁有唯一的值。在我的例子中,成員1在窗口中沒有全部三個日期,而成員2沒有。SQL查找日期是否在一個範圍內

create table #dates (
    member tinyint, 
    bucket tinyint, 
    dt date 
); 

insert into #dates (member,bucket,dt) 
    values (1,1,'20170101'), 
      (1,2,'20161225'), 
      (1,2,'20170204'), 
      (1,3,'20170129'), 
      (2,1,'20170101'), 
      (2,2,'20170102'), 
      (2,3,'20161231'); 

初始查詢

select * 
from #dates d1 join 
    #dates d2 
    on d2.member=d1.member and d2.bucket=2 and 
     d2.dt between DATEADD(DAY,-30,d1.dt) and DATEADD(day,30,d1.dt) 
where d1.bucket=1 
+0

會員1有兩個#2桶,是故意的嗎?你怎麼想象輸出表出現?每個會員有一行有指示符字段? – Snorex

回答

0

如果你想成員,其中這是真的,那麼這是一個方法:

select distinct d.member 
from #dates d 
where exists (select 1 
       from #dates d1 
       where d1.member = d.member and d1.bucket = 1 and 
        d1.dt between DATEADD(DAY, -30, d.dt) and DATEADD(day, 30, d.dt) 
      ) and 
     exists (select 1 
       from #dates d2 
       where d2.member = d.member and d2.bucket = 2 and 
        d2.dt between DATEADD(DAY, -30, d.dt) and DATEADD(day, 30, d.dt) 
      ) and 
     exists (select 1 
       from #dates d3 
       where d3.member = d.member and d3.bucket = 3 and 
        d3.dt between DATEADD(DAY, -30, d.dt) and DATEADD(day, 30, d.dt) 
      ) ; 
相關問題