22,207
社区成员
发帖
与我相关
我的任务
分享
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([aa] varchar(10),[bb] datetime,[cc] int)
insert [tb] select '01','2009-1-1',400
union all select '01','2009-1-3',500
union all select '01','2009-1-4',500
union all select '01','2009-1-29',900
union all select '02','2008-12-5',4000
union all select '02','2008-12-29',300
union all select '02','2009-1-1',5000
union all select '02','2009-2-1',450
select distinct a.*
from tb a
join tb b
on a.aa=b.aa
and a.bb<>b.bb
where abs(datediff(dd,a.bb,b.bb))<=3
/*
aa bb cc
---------- ----------------------- -----------
01 2009-01-01 00:00:00.000 400
01 2009-01-03 00:00:00.000 500
01 2009-01-04 00:00:00.000 500
02 2008-12-29 00:00:00.000 300
02 2009-01-01 00:00:00.000 5000
(5 行受影响)
*/
再加入一个日期调期。小改一下。if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([aa] varchar(10),[bb] datetime,[cc] int)
insert [tb] select '01','2009-1-1',400
union all select '01','2009-1-4',500
union all select '01','2009-1-29',900
union all select '02','2008-12-5',4000
union all select '02','2008-12-29',300
union all select '02','2009-1-1',5000
union all select '02','2009-2-1',450
select a.*
from tb a
join tb b
on a.aa=b.aa
and a.bb<>b.bb
where abs(datediff(dd,a.bb,b.bb))<=3
/*
aa bb cc
---------- ----------------------- -----------
01 2009-01-01 00:00:00.000 400
01 2009-01-04 00:00:00.000 500
02 2008-12-29 00:00:00.000 300
02 2009-01-01 00:00:00.000 5000
(4 行受影响)
*/
select * from tb t where exists (select * from tb where aa=t.aa and abs(datediff(day,aa.tt.aa))<=3)
select * from tb t where exists (select * from tb where aa=t.aa and datediff(day,aa.tt.aa)<=3)
if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([aa] varchar(10),[bb] datetime,[cc] int)
insert [tb] select '01','2009-1-1',400
union all select '01','2009-1-3',500
union all select '01','2009-1-4',500
union all select '01','2009-1-29',900
union all select '02','2008-12-5',4000
union all select '02','2008-12-29',300
union all select '02','2009-1-1',5000
union all select '02','2009-2-1',450
select *
from tb t
where exists
(select 1 from tb where t.aa=aa
and t.bb<>bb and abs(datediff(dd,t.bb,bb))<=3)
/*
aa bb cc
---------- ----------------------- -----------
01 2009-01-01 00:00:00.000 400
01 2009-01-03 00:00:00.000 500
01 2009-01-04 00:00:00.000 500
02 2008-12-29 00:00:00.000 300
02 2009-01-01 00:00:00.000 5000
(5 行受影响)
*/
也可以用exists。