select  b.huowname as '部门名称',a.chkje as '销售出库成本',
cast(sum(c.hwje) as decimal(10,2)) as '现库存金额',
cast(cast(sum(c.hwje)/a.chkje as decimal(10,3))*
(datediff(day,'2008-04-01','2008-04-10')) as int(8)) as '周转天数','本期'as '本期' 
from (select hw,sum(chkje-ml) as chkje 
from splsk 
where chkje >0  group by hw) a ,huoweizl b,hwsp c 
where a.hw=c.hw 
and a.hw=b.hw
and a.hw='HWI00000001'  
group by  b.huowname,a.chkje 
order by b.huowname
union
select a.huowname as '部门名称',b.chbje as '销售出库成本',
cast(sum(c.hwje) as decimal(10,2)) as '现库存金额',
cast(cast(sum(c.hwje)/b.chbje as decimal(10,3))*
(datediff(day,'2008-04-01','2008-04-10')) as int(8)) as '周转天数','本期'as '本期' 
from (select hw,sum(chbje) as chbje
from retmxls 
where rq>='2008-04-01'
and rq<='2008-04-10'
and chbje>0
group by hw) b,huoweizl a,hwsp c
where a.hw=b.hw
and b.hw=c.hw
group by a.huowname,b.chbje
order by a.huowname

解决方案 »

  1.   

    from (select hw,sum(chkje-ml) as chkje  
    from splsk 
    ?
      

  2.   


    --使用union或者union all进行连接时,语句不能进行排序
    select  b.huowname as '部门名称',a.chkje as '销售出库成本', 
    cast(sum(c.hwje) as decimal(10,2)) as '现库存金额', 
    cast(cast(sum(c.hwje)/a.chkje as decimal(10,3))* 
    (datediff(day,'2008-04-01','2008-04-10')) as int(8)) as '周转天数','本期'as '本期'  
    from (select hw,sum(chkje-ml) as chkje  
    from splsk  
    where chkje >0  group by hw) a ,huoweizl b,hwsp c  
    where a.hw=c.hw  
    and a.hw=b.hw 
    and a.hw='HWI00000001'   
    group by  b.huowname,a.chkje  
    --order by b.huowname 
    union 
    select a.huowname as '部门名称',b.chbje as '销售出库成本', 
    cast(sum(c.hwje) as decimal(10,2)) as '现库存金额', 
    cast(cast(sum(c.hwje)/b.chbje as decimal(10,3))* 
    (datediff(day,'2008-04-01','2008-04-10')) as int(8)) as '周转天数','本期'as '本期'  
    from (select hw,sum(chbje) as chbje 
    from retmxls  
    where rq>='2008-04-01' 
    and rq <='2008-04-10' 
    and chbje>0 
    group by hw) b,huoweizl a,hwsp c 
    where a.hw=b.hw 
    and b.hw=c.hw 
    group by a.huowname,b.chbje 
    --order by a.huowname 
      

  3.   

    union 
    前面的有order by 
    后面还有order by 
    ..........
      

  4.   


    --如果一定要排序,可以在外面进行排序,如:
    select * from 
    (select * from a
    union 
    select * from b)m
    order by huowname 
      

  5.   


    --正确写法:
    select * from 
    (select * from a
    union 
    select * from b)m
    order by huowname 
    --错误写法:
    select * from a
    order by huowname
    union 
    select * from b
    order by huowname 
      

  6.   

    select col1 as '我要排名' from a
    union all
    select col2 as '我要排名' from b 
    order by '我要排名'
      

  7.   

    呵呵,只看了列数量是不是一致,没注意order by
    pt正解
      

  8.   


    不用在外面套select
    看8楼
      

  9.   


    不要光想着抢分
    看你这句"--使用union或者union all进行连接时,语句不能进行排序"是多么的误人子弟 
      

  10.   

    去掉第一个order by 
    union 既然合成一个,
    保留最后一个order by 就行了
      

  11.   

    去掉 union 前的order by