我有下面的表格,该表格在2018年和2019年的两年中有重叠的几周。我想为每个使用TSQL的客户确定连续3周的第一套。
结果集应该具有连续3周的第一组的customer_id和max(order_date),如下所示。
答案 0 :(得分:1)
我创建了自己的数据。尝试运行此命令(这使用了2012年及以后的功能的窗口功能):
create table i1(i1 int identity (1,1) primary key, idate date, name varchar(25));
insert into i1 values ('1-1-2019','b'), ('1-8-2019','b'), ('1-15-2019','b'),
('1-1-2019','c'), ('1-8-2019','c'), ('1-24-2019','c'),('1-31-2019','c')
;
with ct1 as (select name,idate, datepart(ww,idate) -lag(datepart(ww,idate),1,0) over (partition by name order by idate) diff
,row_number() over (partition by name order by idate) id from i1),
ct2 as (
select name , idate,sum(diff) over ( partition by name order by idate rows between 3 preceding and current row) diff2
from ct1)
select name, idate
from ct2 where diff2=3