select 物品編號,剩於數量=sum(case 進出標識 when 0 then 入出數量 else -入出數量 end)
from 表
group by 物品編號

解决方案 »

  1.   

    --测试--测试数据
    create table 表(ID int,物品編號 int,進出標識 bit,入出數量 int)
    insert 表 select 1,1001,0,5000
    union all select 2,1002,0,8000
    union all select 3,1001,1,3500
    union all select 4,1001,1,500
    union all select 5,1002,1,300
    go--统计
    select 物品編號,剩於數量=sum(case 進出標識 when 0 then 入出數量 else -入出數量 end)
    from 表
    group by 物品編號
    go--删除测试
    drop table 表/*--测试结果
    物品編號        剩於數量        
    ----------- ----------- 
    1001        1000
    1002        7700(所影响的行数为 2 行)
    --*/
      

  2.   

    调试:
    create table tbl_t4
    (
    i_id int,
    i_gds_id int,
    i_sign int,
    i_cnt int
    )insert into tbl_t4 
    select 
    1,1001,0,5000
    union select 
    2,1002,0,8000
    union select 
    3,1001,1,3500
    union select 
    4,1001,1,500
    union select 
    5,1002,1,300select i_gds_id,sum(case i_sign when 1 then -i_cnt else i_cnt end) from tbl_t4 group by i_gds_id结果:
    i_gds_id                
    ----------- ----------- 
    1001        1000
    1002        7700(所影响的行数为 2 行)