有表a  结构如下 pid        pnum       sid
1           10         01
1           12         02
2           8          01
3           11         01
3           8           03  
其中   pid 为产品编号  pnum为产品数量  sid为仓库id   请用编写sql 语句 实现将上表中的数据合并pid   s1id      s2id               s3id1      10         12               0
2      8           0               0
3      11          0               8   s1id   为仓库01 的库存量  
s2id   为仓库02 的库存量  
s3id   为仓库03 的库存量  
如果该产品在某仓库中无库存量  用0代替

解决方案 »

  1.   

    CREATE TABLE a (pid varchar(20),pnum int,sid varchar(20))
    INSERT INTO a
    SELECT '1','10','01' union all
    SELECT '1','12','02' union all
    SELECT '2','8','01' union all
    SELECT '3','11','01' union all
    SELECT '3','8','03'  select pid,sum(case sid when '01' then pnum else 0 end) as s1id,
               sum(case sid when '02' then pnum else 0 end) as s2id,
               sum(case sid when '03' then pnum else 0 end) as s3id 
     from a group by pidDROP TABLE a
      

  2.   

    if not object_id('tb1') is null
    drop table tb1
    Go
    Create table tb1(pid int,pnum int,sid nvarchar(2))
    Insert tb1
    select 1,10,N'01' union all
    select 1,12,N'02' union all
    select 2,8,N'01' union all
    select 3,11,N'01' union all
    select 3,8,N'03'
    Go
    select 
    pid,
    sum(case when [sid]='01' then pnum else 0  end) as s1id,
    sum(case when [sid]='02' then pnum else 0  end) as s2id,
    sum(case when [sid]='03' then pnum else 0  end) as s3id
    from tb1
    group by pid