34,590
社区成员
发帖
与我相关
我的任务
分享
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'
;with cte as
(
select *,row_number() over (order by id,getdate()) m from #test
)
select id,dt from cte a where
not exists (select 1 from cte where id=a.id and m=a.m+1 and
abs(datediff(mi,dt,a.dt))<10)
/*
id dt
----------- -----------------------
1 2014-05-03 09:16:23.000
2 2014-05-03 09:17:23.000
2 2014-05-03 09:27:23.000
*/
WITH t (ID,DateTime) AS
(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'
)
, t2 AS (SELECT ROW_NUMBER() OVER (PARTITION BY id ORDER BY id ,DateTime )AS id1,* FROM t )
SELECT * FROM t2 AS aa WHERE NOT exists (SELECT * FROM t2 AS bb WHERE aa.id1+1=bb.id1 AND aa.id =bb.id AND DATEADD(minute,10,aa.datetime) > bb.datetime)
结果
1 2014-05-03 09:26:23.000
1 2014-05-03 09:36:23.000
2 2014-05-03 09:17:23.000
2 2014-05-03 09:27:23.000
2 2014-05-03 09:37:23.000
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