2017-05-04 106 views
2

我试图获得所有具有乘以两列值的行的总和,以及条件但是获取了一些mysql错误。尝试过了一些例子,我实现我的结果,但我不知道这是正确的方式或不:MySQL:代表第三列获得乘以两列的列的总和

表:store_stocks

enter image description here

我只是想乘算库存数量与金额数量根据含增值税,不含增值税和总库存。

我刚刚创建的查询:

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 

其显示结果:

enter image description here

任何一个可以告诉我有没有另一种方式来做到这一点,因为我认为这是查询有点复杂,每次我使用子查询中的位置,我也必须在laravel eloquent中实现此查询。

回答

1

你不需要的子查询,你可以使用条件的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 

您可以使用,而不是if()功能case表达。

+0

其在第2行显示错误'as non_vat_stock, sum(if(vat_status = 1,qty * sale_price,0)as with_vat' –

+0

错误关闭')'两次。但是,请不要复制粘贴解决方案,也要尝试理解它。 – Shadow

+0

哇..大!! –