【问题标题】:MySQL getting total sum of all rows using casesMySQL使用案例获取所有行的总和
【发布时间】:2015-11-02 22:12:19
【问题描述】:

我有一个 MySQL 表,它在用户使用凭单付款时记录数据库中的值。它记录凭证价值。我需要得到按代金券金额细分的所有代金券价值的总和。我目前的查询如下。但是 butchery_class_voucher_155butchery_class_voucher_135 总是返回为 0。

请帮忙解决这个问题。

select 
case 
    when voucher_value = '155.00' 
    then round(sum(voucher_value/1.2), 2) 
    else 0.00 end 
as butchery_class_voucher_155,
case 
    when voucher_value = '10.00' 
    then round(sum(voucher_value/1.2), 2) 
    else 0.00 end 
as shop_voucher,
case when voucher_value = '135.00'      
    then round(sum(voucher_value/1.2), 2) 
    else 0.00 end 
as butchery_class_voucher_135,
ifnull(round(sum(final_price/1.2), 2),0.00) as paidbycard,
ifnull(round(sum(transfer_fee/1.2), 2),0.00) as transfer_fee 
    from `bookings` 
where `location_id` = 6

【问题讨论】:

  • voucher_value 是文本字段吗?
  • 不,是小数 decimal(9,2)
  • 那你为什么要做文本比较?
  • @SunKnight0 - 即使我使用 ` = 155` 我仍然得到 0.00 作为结果。
  • @SunKnight0: 没关系,因为 MySQL 会进行隐式转换

标签: mysql sql


【解决方案1】:

问题是你在一个案例中调用了 sum(),即使案例(或 ifs)应该在 sum() 中。使用您当前的代码,如果第一条记录的 voucher_value 为 10,那么只有 shop_voucher 表达式会给您除零以外的任何结果。

select 
    round(sum(if(voucher_value=155,voucher_value/1.2,0)), 2) as butchery_class_voucher_155,
    ...
    from `bookings` 
where `location_id` = 6

您还需要考虑一件事:将舍入函数放在哪里。您可以先对结果求和,然后对其进行四舍五入(这是我上面代码中使用的内容),或者您可以在每个除法处应用四舍五入。

【讨论】:

    【解决方案2】:

    失败的原因是您设置案例陈述的方式。如果凭证值等于某个值,您已经编写了一个查询来给您总和,或者给您零。在查询分析的最后一行,它只会比较该凭证值,其他的将返回为 0。

    要解决这个问题,你需要调整你的SUM()函数,在值匹配的情况下添加凭证值,否则添加0:

    SELECT ROUND(SUM(CASE WHEN voucher_value = 155 THEN (voucher_value / 1.2) ELSE 0 END), 2) AS butchery_class_voucher_155...
    

    等等。

    【讨论】:

      猜你喜欢
      • 2016-02-06
      • 2017-09-03
      • 1970-01-01
      • 2020-12-31
      • 1970-01-01
      • 2011-09-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多