Select id,sum(case when state = '03' then num else 0 end) - sum(case when state = '01' then num else 0 end) 
group by id

解决方案 »

  1.   

    1:
    Select id,sum(case when state = '03' then num else 0 end) - sum(case when state = '01' then num else 0 end) 
    from 表
    group by id
    2:
    Select id,sum(case state when '03' then num when '01' then -num else 0 end) 
    from 表
    group by id
      

  2.   

    create table t1(id int,state char(2),num int)
    insert t1 select     2,       '01',12
    union all select     2 ,      '03',11
    union all select     3  ,     '03',15
    union all select     5   ,    '01',10
    union all select     3    ,   '01',132
    union all select     2     ,  '01',2
    union all select     5      , '03',11:
    Select id,sum(case when state = '03' then num else 0 end) - sum(case when state = '01' then num else 0 end) 
    from t1
    group by id
    id                      
    ----------- ----------- 
    2           -3
    3           -117
    5           -9(所影响的行数为 3 行)
    2:
    Select id,sum(case state when '03' then num when '01' then -num else 0 end) 
    from t1
    group by id
    id                      
    ----------- ----------- 
    2           -3
    3           -117
    5           -9(所影响的行数为 3 行)
      

  3.   

    Select id,sum(case when state = '03' then num else 0 end) - sum(case when state = '01' then num else 0 end)  from 表 group by id
      

  4.   

    select id,sum(case state when '03' then num when '01' then -num else 0 end) 和 from 表 group by id
      

  5.   

    select ID, isnull(sum(case when state = '03' then num else 0 end),0)
     - isnull(sum(case when state = '01' then num else 0 end),0) 
    from table1 group by ID