我正在处理总和,如果,我能够获得Sum的数字的值(amount_description),但我不知道如何基于文本(varchar和蓝色突出显示)进行计算。
正如您可以看到屏幕截图为金额,我希望根据每个SKU的金额描述计算金额
所以我希望你可以提供建议和工作方式
我尝试了很多方法,但即使我写了
,也没有任何工作要做SELECT SUM(CASE WHEN amount_description = 'commission' and amount_description = 'Commission' and amount_description = 'RefundCommission'THEN amount END) AS sku_TOTAL, transaction_type
FROM settlements
Where transaction_type ='refund'
我仍然是mysql的新手。
答案 0 :(得分:1)
您好,您可以使用group by和sum来获取每个amount_description的总和,然后使用having或where来获取只有一些amount_descriptions来过滤它们
请尝试
SELECT SUM(amount) AS total, amount_description
FROM settlements
Where transaction_type ='refund'
GROUP BY amount_description
having amount_description="commission" or amount_description="Commission" or
amount_description="RefundCommission"
OR
SELECT SUM(amount) AS total, amount_description,sku
FROM settlements
WHERE transaction_type ='refund'
AND ( amount_description="commission" OR amount_description="Commission" OR
amount_description="RefundCommission" )
GROUP BY amount_description,sku
答案 1 :(得分:1)
您可以使用SUM
功能以及GROUP BY
将具有相同SKU的所有条目组合在一起。
SELECT
`transaction_type`,
`sku`,
SUM(`amount`) AS `sku_total`
FROM
`settlements`
WHERE
`transaction_type` = 'Refund'
AND `amount_description` IN (
'Principal', 'Commission', 'RefundCommission'
)
GROUP BY
`transaction_type`, -- Doesn't really do anything since there is only one type
`sku`
关于没有做任何事情的评论:MySQL通常会在没有这个的情况下允许这个查询,但大多数DBMS要求所有不在聚合函数中的字段必须在GROUP BY
子句中。在这种情况下,因为只有一个组(退款),它不会影响输出,应该包含在最佳实践中。