我有个表
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语句怎么写?
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语句怎么写?
from (
select type,sum(value) as all
from tb
group by type
)T
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 行)
*/