我试图通过将两个列值与 where 条件相乘来获取所有行的总和,但出现了一些 mysql 错误。在尝试了一些例子后,我得到了我的结果,但我不知道那是不是正确的方法:
表:store_stocks
我只想根据增值税、非增值税和总库存计算库存数量,数量乘以数量。
我刚刚创建了那个查询:
SELECT sum(qty*sale_price) as total_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 0 and store_id = 8) as non_vat_stock,
(select sum(qty*sale_price) from store_stocks where vat_status = 1 and store_id = 8) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
及其显示结果:
谁能告诉我有没有其他方法可以实现这个,因为我认为这个查询有点复杂,每次我在子查询中使用 where 并且我还必须在 laravel eloquent 中实现这个查询
。
最佳答案
你不需要子查询,你可以在 sum()
中使用一个条件,让它只汇总特定的记录:
SELECT sum(qty*sale_price) as total_stock,
sum(if(vat_status = 0, qty*sale_price, 0)) as non_vat_stock,
sum(if(vat_status = 1, qty*sale_price, 0)) as with_vat_stock
FROM `store_stocks` where store_id = 8 group by store_id
您也可以使用 case
表达式代替 if()
函数。
关于MySQL:代表第三列将两列相乘得到列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43774054/