MySQL使用案例获取所有行的总和

V4n1ll4

我有一个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
阴影

问题在于,即使案例(或ifs)应位于sum()内,您也可以在案例内调用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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章