我有这样一张桌子:
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 145与product_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它的瞬间?
如果我理解正确,这只是一个使用条件聚合的查询:
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)
| 归档时间: |
|
| 查看次数: |
58 次 |
| 最近记录: |