使用tsql,我试图在30天的窗口内查找成员是否有来自三个独立存储桶中的每一个的服务。水桶不一定具有独特的价值。在我的例子中,成员1在窗口中没有所有三个日期,而成员2则没有。
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');
INITIAL QUERY
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 :(得分: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)
) ;