34,596
社区成员
发帖
与我相关
我的任务
分享
对于每一行求出 与该行对应该id的最小日期相差的天数 ,如果天数除以90得到的数相同,则为一组
create table test
(
id int,
dt datetime
);
insert into test
select 1,'2012-01-01'
union all select 1, '2012-02-06'
union all select 1, '2012-05-03'
union all select 1, '2012-06-11'
union all select 1, '2012-09-01'
union all select 2, '2012-02-03'
union all select 2, '2012-04-19'
union all select 2, '2012-04-23'
;with cte as (select id,MIN(dt) as dt from test group by id)
select A.id,MIN(A.dt) as dt,COUNT(1) as N
from test as A
inner join cte as B on A.id=B.id
group by A.id,datediff(DAY,B.dt,A.dt)/90
order by A.id,dt;
drop table test;
id dt N
----------- ----------------------- -----------
1 2012-01-01 00:00:00.000 2
1 2012-05-03 00:00:00.000 2
1 2012-09-01 00:00:00.000 1
2 2012-02-03 00:00:00.000 3
(4 行受影响)