我有个表
ID  type  value
1   1     10
2   1     14
3   2     5
4   1     6
5   2     12我需要求一个tpye=1的value的和减去type=2的value的和 的差
即(10+14+6)-(5+12)= 13
我最后要得到13 请问sql语句怎么写?

解决方案 »

  1.   

    select (case when type=1 then all end) -(case when type=2 then all end)
    from (
    select type,sum(value) as all
    from tb
    group by type
    )T
      

  2.   

    select (case when type = 1 then value else - values end) from tb
      

  3.   

    忽略我2楼的写法,
    create table tb(ID int,type int,value int)
    insert into tb values(1 ,1 ,10)
    insert into tb values(2 ,1 ,14)
    insert into tb values(3 ,2 ,5)
    insert into tb values(4 ,1 ,6)
    insert into tb values(5 ,2 ,12)
    goselect sum(case when type = 1 then value else - value end) from tbdrop table tb/*
                
    ----------- 
    13(所影响的行数为 1 行)
    */