有以下数据表:
ID DateTime
1 2014-05-03 09:17:23
1 2014-05-03 09:17:23
1 2014-05-03 09:16:23
2 2014-05-03 09:17:23
2 2014-05-03 09:27:23
要得出:同一个ID号的,10分钟之内的数据,只保留最新的一条
即可以得到下列结果:
ID DateTime
1 2014-05-03 09:16:23
2 2014-05-03 09:17:23
2 2014-05-03 09:27:23
------解决方案--------------------
drop table #test
create table #test(id int,dt datetime)
insert into #test(id,dt)
select '1','2014-05-03 09:17:23' union all
select '1','2014-05-03 09:17:23' union all
select '1','2014-05-03 09:16:23' union all
select '2','2014-05-03 09:17:23' union all
select '2','2014-05-03 09:27:23' union all
select '2','2014-05-03 09:37:23' union all
select '1','2014-05-03 09:25:23' union all
select '1','2014-05-03 09:26:23' union all
select '1','2014-05-03 09:36:23'
select x.id,x.dt from
(select a.id,a.dt,row_number() over(order by id,dt) as uid
from #test a) x
where not exists(select 1 from #test z where z.id=x.id and z.dt>x.dt)
or exists(select 1 from (select a.id,a.dt,row_number() over(order by id,dt) as uid
from #test a) y where y.id=x.id and y.uid=x.uid+1 and datediff(mi,x.dt,y.dt)>9 )
group by x.id,x.dt