日期:2014-05-18  浏览次数:20395 次

sql 相邻记录的不同字段(字段类型为DataTime)相比较
一个A表数据如下:

单号 送修时间     维修完成时间
1 2011-10-9       2011-10-28
2 2011-10-25     2011-10-31
3 2011-11-16     2011-12-30

第二行的送修时间与第一行的维修完成时间的差,小于或者等于30,就把这条记录显示出来

效果如图:

单号 送修时间     维修完成时间
1 2011-10-9       2011-10-28
2 2011-10-25     2011-10-31

请教各位大虾指教指教,用sql怎样写才能得到效果图的数据??

------解决方案--------------------
SQL code
create table tb(单号 int,条码 varchar(10),送修时间 datetime,维修完成时间 datetime)
insert into tb select 1,'A','2011-10-9','2011-10-10'
insert into tb select 2,'A','2011-10-15','2011-10-31'
insert into tb select 3,'A','2011-12-16','2011-12-30'
insert into tb select 4,'B','2011-9-10','2011-9-15'
insert into tb select 5,'B','2011-11-10','2011-11-20'
insert into tb select 6,'C','2011-12-1','2011-12-3'
insert into tb select 7,'C','2011-12-5','2011-12-6'
go
select * from tb a 
where exists(select 1 from tb where 条码=a.条码 and 单号<>a.单号 and abs(datediff(d,送修时间,a.维修完成时间))<30)
/*
单号          条码         送修时间                    维修完成时间
----------- ---------- ----------------------- -----------------------
1           A          2011-10-09 00:00:00.000 2011-10-10 00:00:00.000
2           A          2011-10-15 00:00:00.000 2011-10-31 00:00:00.000
6           C          2011-12-01 00:00:00.000 2011-12-03 00:00:00.000
7           C          2011-12-05 00:00:00.000 2011-12-06 00:00:00.000

(4 行受影响)

*/
go
drop table tb