gpt4 book ai didi

MySQL计算同一列中的百分比

转载 作者:行者123 更新时间:2023-11-29 17:15:27 24 4
gpt4 key购买 nike

在下表中,我如何计算每位客户的食品成本占总成本的百分比?希望将“食品成本”乘以 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 错误“错误代码:1242。子查询返回的值大于 1”行”。

最佳答案

您可以在此处使用条件聚合来获取每个客户的食品和总成本记录:

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

关于MySQL计算同一列中的百分比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51664268/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com