表如下:
 收发标志       货物       数量
   1            0001        20
   1            0002        30
   0            0001         5
   1            0002        20
   0            0002         6(收发标志1为收到,0为发出)
要得到结果如下:货物     收到数量         发出数量
0001      20                 5
0002      50                 6 请问我要如何实现啊?

解决方案 »

  1.   

    --建立测试环境
    Create Table 表(收发标志 varchar(10),货物 varchar(10),数量 integer)
    --插入数据
    insert into 表
    select '1','0001','20' union
    select '1','0002','30' union
    select '0','0001','5' union
    select '1','0002','20' union
    select '0','0002','6'
    select * from 表
    --测试语句
     select 货物,
    数量1=sum(case when 收发标志=0 then 数量 else 0 end),
    数量2=sum(case when 收发标志=1 then 数量 else 0 end)
     from 表
    group by 货物
     
    --删除测试环境
    Drop Table 表
      

  2.   


    和樓上的完全一致,早知道我就不寫了,不過寫了就傳上來吧Create Table 表(收发标志 varchar(10),货物 varchar(10),数量 integer)
    go
    insert into table1
    select '1','0001','20' union
    select '1','0002','30' union
    select '0','0001','5' union
    select '1','0002','20' union
    select '0','0002','6'
    select * from table1
    go
     select hw,
    sd=sum(case when 收发标志=0 then 数量 else 0 end),
    fs=sum(case when 收发标志=1 then 数量 else 0 end)
     from table1
    group by 货物