减去/总结一张桌子

S.M*_*ian 3 mysql sql

我有这样一张桌子:

id product_property_id product_id amount type
1       1                  145      10    0
2       4                  145      12    0
3       6                  145      13    1
4       23                 147      2     0
5       4                  145      15    1 
6       4                  145      2     1   
Run Code Online (Sandbox Code Playgroud)

type :

0:出

1:进

我想要的是 :

例如 :

product_id 145product_property_id 4:

(15 + 2) - 12 = 5

product_id   product_property_id  new_amout
  145              4                  5
Run Code Online (Sandbox Code Playgroud)

有可能用来SQL得到这个结果,或者我必须使用php它的瞬间?

Gor*_*off 7

如果我理解正确,这只是一个使用条件聚合的查询:

select product_id, product_property_id,
       sum(case when type = 1 then amount
                when type = 0 then - amount
                else 0
           end) as new_amount
from likethis
group by product_id, product_property_id;
Run Code Online (Sandbox Code Playgroud)

  • 使用算术表达式总是比条件逻辑更有趣:`sum((2*type-1)*amount)`;) (2认同)
  • @symcbean,也许是真的,但无法维护的代码. (2认同)