MySQL:代表第三列将两列相乘得到列的总和

标签 mysql eloquent laravel-5.3

我试图通过将两个列值与 where 条件相乘来获取所有行的总和,但出现了一些 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

谁能告诉我有没有其他方法可以实现这个,因为我认为这个查询有点复杂,每次我在子查询中使用 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/

相关文章:

mysql - sql检查select返回null

laravel - 为什么laravel eloquent模型保存后没有id?

mysql - 检查mysql是否有索引null

mysql - 我有一个与数据库中大多数其他表相关的表。将其添加为联接是否足以使查询按预期返回?

mysql - 如果我们定义的列长度超过要求会怎样?

php - 如何使用 with 关键字在 Laravel 中获取数据和关系数据?

php - 尝试从旨在提交多条记录的表单中插入 user_id 和数组时收到错误

php - Laravel 连接外部数据库?

php - 当我在 laravel 的 View 页面上调用 foreach 循环时,它不显示数据

html - 为什么打印的时候图片在div外面?