Case when then else 用法例子
问题:
T表:
TID Quantity ProductID Type
1 2 12 1
2 6 12 2
5 3 10 2
7 8 10 1
其中Type=1表示卖,Type=2表示买,ProductID为商品ID,
现在要计算现有的每种商品有多少件,该怎么写这个SQL语句
解决方法:
declare @T table(TID int,Quantity int,ProductID int,Type int)
insert into @T select 1,2,12,1
insert into @T select 2,6,12,2
insert into @T select 5,3,10,2
insert into @T select 7,8,10,1
select
ProductID,sum(case Type when 1 then Quantity else -Quantity end) as Quantity
from
@T
group by
ProductID
/*
ProductID Quantity
----------- -----------
10 5
12 -4
*/
浙公网安备 33010602011771号