日期:2014-05-16  浏览次数:20861 次

union all 使用问题

select c.pm,c.rq,c.jg as ttjg,d.jg as pfjg,to_char(((d.jg-c.jg)/c.jg)*100,'999.99') as TTPF_RATE,''LSPF_RATE,''TTLS_RATE,''lsjg from
(select * from ttsc where c_id=100500)c,
(select * from pfsc where c_id=100100 and pm in (select product from tt_product))d
where c.rq=d.rq and c.pm=d.pm  
 union all
select c.product_name pm,c.rq,c.jg lsjg,d.jun pfjg,to_char(((jg-jun)/jun)*100,'999.99') as LSPF_RATE,'' TTPF_RATE,'' TTLS_RATE,''ttjg from (
 select a.*,b.pf_id from lingshou a left join LS_PF_PRODUCT b on a.product_name=b.ls_product
 where a.product_name in b.ls_product
)c left join
(select rq,s_id,jun from pfsc where mc='所有市场' and s_id in (select pf_id from ls_pf_product)) d
on c.rq=d.rq and c.pf_id=d.s_id  
 union all
select d.pm,d.weekday as rq,d.weekavgprice as ttjg,c.jg as lsjg,to_char(((c.jg-d.weekavgprice)/d.weekavgprice)*100,'999.99') as ttls_rate, '' TTPF_RATE,''LSPF_RATE,''pfjg from
(select product_name, rq,  jg,
(select trunc(rq - 7,   'DD') -  to_char(rq - 7, 'D') + 8 sdate  from dual) lastsunday
 from lingshou where  product_name in (select product from tt_product)
 )c ,( select a.*,b.pm from jgjk_weekprice a , JGJK_CPFL b where a.canton_id=100500 and a.sp_id=b.id)d
 where c.lastsunday=d.weekday and d.pm=c.product_name 
 这是sql


union all 后为什么这写字段 LSPF_RATE,TTLS_RATE,lsjg 都是空
------解决方案--------------------
给你举个例子:
select 1 a,2 b from dual union all
select 3,'' from dual union all
select '',3 from dual 
类似于这个样子,union all的结果是以第一个sql查出来的结果为准的,后面的sql是将结果集并入第一个sql结果集中,所以
要保证后面的sql的字段顺序、个数、类型都要与第一个保持一致才可以。。
所以你第二段sql和第三段sql定义的别名是没有任何作用的。。你只需要保证字段顺序对就可以了。。