--一条语句就真的过分了,因为你的货位是动态的,这样写吧declare @s varchar(8000)
set @s=''
select @s=@s+',[库位'+商品库位+']=sum(case 商品库位 when '''+商品库位+''' then 库存数量 else 0 end)'
from 表
group by 商品库位
exec('select 商品ID,商品名'+@s+'
from 表
group by 商品ID,商品名')

解决方案 »

  1.   


    昏,一楼来了一个跟我一样笨的。HOHO
      

  2.   

    --上面少了合计declare @s varchar(8000)
    set @s=''
    select @s=@s+',[库位'+商品库位+']=sum(case 商品库位 when '''+商品库位+''' then 库存数量 else 0 end)'
    from 表
    group by 商品库位
    exec('select 商品ID,商品名'+@s+',合计=sum(库存数量)
    from 表
    group by 商品ID,商品名')
      

  3.   

    --测试--测试数据
    create table 表(商品ID char(3),商品名 varchar(10),商品库位 char(4),库存数量 int)
    insert 表 select '001','冰箱','A001',3
    union all select '002','电视','A001',3
    union all select '003','空调','A001',3
    union all select '001','冰箱','A002',3
    union all select '001','冰箱','A003',3
    go--查询
    declare @s varchar(8000)
    set @s=''
    select @s=@s+',[库位'+商品库位+']=sum(case 商品库位 when '''+商品库位+''' then 库存数量 else 0 end)'
    from 表
    group by 商品库位
    exec('select 商品ID,商品名'+@s+',合计=sum(库存数量)
    from 表
    group by 商品ID,商品名')
    go--删除测试
    drop table 表/*--测试结果商品ID 商品名        库位A001      库位A002      库位A003      合计          
    ---- ---------- ----------- ----------- ----------- ----------- 
    001  冰箱         3           3           3           9
    002  电视         3           0           0           3
    003  空调         3           0           0           3
    --*/