MySQL在同一列中计算百分比

时间:2018-08-03 01:50:28

标签: mysql

在下表中,我如何计算每个客户的食品成本占总成本的百分比? 希望将“食品成本”乘以100,然后除以“总成本”。例如,客户1将返回39.5。

+------------+------------+--------+
| customerId |  category  | total  |
+------------+------------+--------+
|          1 | Food Cost  |  65031 |
|          1 | Total Cost | 164637 |
|          2 | Food Cost  |  72031 |
|          2 | Total Cost | 264637 |
+------------+------------+--------+


SELECT round(total * 100 / (SELECT total FROM table where category = "Total 
Cost" and customerId = 1), 2) as Total FROM table where category = "Food 
Cost" and customerId = 1;

这将为我提供客户1所需的结果,但是如果我想同时返回两个客户,则需要删除customerId =“”,这将返回MySQL错误“ Error Code:1242。子查询返回的结果多于1行”。

2 个答案:

答案 0 :(得分:0)

您可以在此处使用条件汇总来获取每个客户的食物和总费用记录:

SELECT
    customerId,
    100.0 * MAX(CASE WHEN category = 'Food Cost' THEN total END) /
    MAX(CASE WHEN category = 'Total Cost' THEN total END) AS percentage
FROM yourTable
GROUP BY customerId;

enter image description here

Demo

答案 1 :(得分:0)

我最终使用了这个

SELECT ROUND(food.total * 100 / total.total, 1) AS 'Food Total'
FROM table AS food 
INNER JOIN table as total on food.customerId = total.customerId
WHERE food.category = 'Food Cost'
AND total.category = 'Total Cost';