日期:2014-05-17  浏览次数:20514 次

怎么做这种多表查询带条件判断的
SQL code

我要查询小于或等于5月份的数据,对两个表里面的数据进行查询,条件先查询表2里在面的数据,如果表2里面没有了再查表1里面的。
判断小于或等于5月份,条件可以这样写
convert(varchar(7),a.MontrDate,120)>=convert(varchar(7),‘2012-05-01’,120)
/*
表2
Numbers  post  MontrDate
001       12   2012-05-01
003       12   2012-04-03
表1
Numbers  post  
001       23   
003       24
004       36   

这样的表结果
要查询出来的结果

Numbers  post 
001       12  
003       12  
004       36  
*/



------解决方案--------------------
SQL code
;with tt2 as(
select Numbers,  post from 表2 where convert(varchar(7),MontrDate,120)>='2012-05'
)
select * from tt2
union all
select * from 表1 tt1 where not exists(select 1 from tt2 where Numbers=tt1.Numbers)