求离当前时间最近的纪录(在线等!急急急急急急!!!)
表1 M :IN_NO IN_DATE
1 20070718
2 20070719
3 20070218
表2 N :IN_NO CODE PRICE
1 001 1000
2 001 100
3 002 100
条件:M.IN_NO=N.IN_NO DATEDIFF(DAY,M.IN_DATE, '20070720 ')为最小
结果:MAT_CODE PRICE
001 100
002 100
------解决方案--------------------create table t1(IN_NO int,IN_DATE varchar(10))
insert t1
select 1 , '20070718 '
union select 2, '20070719 '
union select 3, '20070218 '
create table t2(IN_NO int,CODE varchar(10),PRICE int)
insert t2
select 1 , '001 ',1000
union select 2, '001 ',100
union select 3, '002 ' ,100
select * from (select MAT_CODE=a.CODE,PRICE,b.IN_DATE from t1 b inner join t2 a on a.in_no=b.in_no) t
where not exists(select 1 from (select MAT_CODE=a.CODE,PRICE,b.IN_DATE from t1 b inner join t2 a on a.in_no=b.in_no) d where t.MAT_CODE=MAT_CODE and t.IN_DATE <IN_DATE)
drop table t1,t2