try:
Select aa.* from table1 aa
join (select sj from table1 where b is null) bb
  on abs(datediff(minute,aa.sj,bb.sj)) <= 5
where aa.b is not null

解决方案 »

  1.   

    测试:
    create table table1 (sj datetime,a char(10),b char(10))
    insert table1 select '2003-10-20 9:10:11','aaaa','b'
    Union all select '2003-10-20 9:11:11','xxxx',null
    Union all select '2003-10-20 9:11:30','xxxr',null
    Union all select '2003-10-20 9:11:50','xxxr','b'
    Union all select '2003-10-20 9:12:11','xxxr','bb'
    Union all select '2003-10-20 9:34:11','xxxr',null
    Union all select '2003-10-20 9:35:11','xxxr','b'
    Union all select '2003-10-20 9:35:45','xxxr','b'
    Union all select '2003-10-20 9:36:11','xxxr',null
    Union all select '2003-10-20 10:20:45','xxxr','b'
    Union all select '2003-10-20 10:20:45','xxxr','b'Select distinct aa.* from table1 aa
    join (select sj from table1 where b is null) bb
      on abs(datediff(minute,aa.sj,bb.sj)) <= 5
    where aa.b is not null
    sj                                                     a          b          
    ------------------------------------------------------ ---------- ---------- 
    2003-10-20 09:10:11.000                                aaaa       b         
    2003-10-20 09:11:50.000                                xxxr       b         
    2003-10-20 09:12:11.000                                xxxr       bb        
    2003-10-20 09:35:11.000                                xxxr       b         
    2003-10-20 09:35:45.000                                xxxr       b         (所影响的行数为 5 行)
      

  2.   

    Select A.* from table1 A inner join 
         (select sj from table1 where b is null) B
           on abs(datediff(minute,A.sj,B.sj)) <= 5
    where A.b is not null