【问题标题】:MySQL: get sum of columns with multiply two columns on behalf of third columnMySQL:获取代表第三列乘以两列的列总和
【发布时间】:2017-05-04 04:44:04
【问题描述】:

我试图通过将两列值与 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 中实现这个查询。

【问题讨论】:

    标签: mysql eloquent laravel-5.3


    【解决方案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
    

    您也可以使用case 表达式代替if() 函数。

    【讨论】:

    • 第 2 行显示错误 'as non_vat_stock, sum(if(vat_status = 1, qty*sale_price, 0) as with_vat'
    • 两次错过关闭)。但请不要只是复制粘贴解决方案,还要尝试理解它。
    • 我的意思是,你甚至没有尝试找到错误的根源,只是将错误消息粘贴回来。
    • 是的,我同意你的看法.. 先生下次我会记住的 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 1970-01-01
    • 2011-04-17
    • 2014-05-11
    • 1970-01-01
    • 2015-05-02
    • 2019-05-29
    相关资源
    最近更新 更多