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

union 与order by 联合使用问题解决方案
1、select     '前20位单品 '   Col1, ' '   Col2, ' '   Col3, ' '   Col4    
2、select   top   20   b.spbm,b.spmc,cast(sum(a.spsl)   as   varchar(20))   数量,cast(sum(a.zxssze)   as   varchar(20))   金额
from   uv_saledetail   a,uv_spbaseinfo   b
where   a.spbm=b.spbm   and   posid   in   ( '31 ', '32 ')   and   xsrq= '2007-01-13 '
group   by   b.spbm,b.spmc  
order   by   sum(a.spsl)   desc

以上两条SQL语句单独执行没任何问题,现在当我写成如下则出现错误提示:
select     '前20位单品 '   Col1, ' '   Col2, ' '   Col3, ' '   Col4    
union   all   -----加上(:   union   all   :)
select   top   20   b.spbm,b.spmc,cast(sum(a.spsl)   as   varchar(20))   数量,cast(sum(a.zxssze)   as   varchar(20))   金额
from   uv_saledetail   a,uv_spbaseinfo   b
where   a.spbm=b.spbm   and   posid   in   ( '31 ', '32 ')   and   xsrq= '2007-01-13 '
group   by   b.spbm,b.spmc  
order   by   sum(a.spsl)   desc
执行结果:
服务器:   消息   107,级别   16,状态   2,行   1
列前缀   'a '   与查询中所用的表名或别名不匹配。
请问各位高手如何解决




------解决方案--------------------
select '前20位单品 ' Col1, ' ' Col2, ' ' Col3, ' ' Col4
union all
select * from
(select top 20 b.spbm,b.spmc,cast(sum(a.spsl) as varchar(20)) Col3,cast(sum(a.zxssze) as varchar(20)) Col4
from uv_saledetail a,uv_spbaseinfo b
where a.spbm=b.spbm and posid in ( '31 ', '32 ') and xsrq= '2007-01-13 '
group by b.spbm,b.spmc) T
order by col3
------解决方案--------------------

select '前20位单品 ' Col1, ' ' Col2, ' ' Col3, ' ' Col4
union all
select * from
(select top 20 b.spbm,b.spmc,cast(sum(a.spsl) as varchar(20)) Col3,cast(sum(a.zxssze) as varchar(20)) Col4
from uv_saledetail a,uv_spbaseinfo b
where a.spbm=b.spbm and posid in ( '31 ', '32 ') and xsrq= '2007-01-13 '
group by b.spbm,b.spmc) T
order by case col3 when ' ' then 0 else 1 end ,col3 desc --這樣??