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

解决方案 »

  1.   

    哥们,你的写发执行果然不出错误,但是不是我想要的结果哈,我要的是第二条SQL执行的结果知道吗,也就是要按降序排列的前20名
      

  2.   

    lz,你的SQL语法上是没有问题的。
      

  3.   

    order by sum(a.spsl) desc --這一行錯對union all結果排序只能引用第一個SELECT的列
      

  4.   


    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 --這樣??
      

  5.   

    楼上哥们,先谢谢你热心,不过你的结果不对哈,假设有表如下:
    编码              名称              数量      金额   
    2503005900 银耳粥          98.00 98.00
    2507000500 鲜草莓冰糖葫芦 96.00 192.00
    2502000900 羊肉串 91.00 91.00
    1751007099 Z9玉米棒子(大) 9.00 22.50
    2507002800 夹巧克力冰糖葫芦 9.00 13.50
    2502002000 川香排骨 81.00 162.00
    2501000500 芥末牛肉春卷 8.00 16.00
    2502001600 鸡排 8.00 8.00
    2503001900 蛋炒饭大份 8.00 24.00
    2507000600 夹核桃冰糖葫芦 8.00 16.00
    2507001900 香蕉馅冰糖葫芦 8.00 12.00
    2507002600 沾朱古力冰糖葫芦 8.00 12.00
    2503003700 孜然肉丝炒面小份 72.00 216.00
    2501000900 红糖冰粉 7.00 7.00
    2502000200 鲜果汁 7.00 24.50
    2503000500 排骨火锅粉大份 7.00 35.00
    2504000500 鸡肉 64.00 25.60
    1735017799 Z9柚子 6.38 23.00
    1751000699 Z9鸡蛋薄饼 6.00 7.20
    2503000600 排骨火锅粉小份 6.00 27.00
    我要得到销售金额前10名的商品,SQL 应该如下:
    select top 10 b.spbm,rtrim(ltrim(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 order by Col4  desc 
    但加上抬头:select  '前20位单品' Col1,'' Col2,'' Col3,'' Col4  不对???????????