如何计算总和栏的百分比?

时间:2019-06-14 06:35:33

标签: mysql

我要计算我有下表的累计金额列的百分比

id  amount cumulative_amount
1   10000  10000
2   15000  25000
3    5000  30000
4   10000  40000

我希望输出为

id  amount cumulative_amount  percentage
1   10000  10000              100%
2   15000  25000              166.67% (i.e cumulative_amount*100/amount)
3    5000  30000              600%
4   10000  40000              400%

那么如何在mysql中编写查询以实现上述输出

我在下面的查询中写了

SELECT amount,SUM(amount) OVER(ORDER BY id) AS cumulative_amount,
concat(round((cumulative_amount/amount * 100 ),2),'%') AS percentage
FROM mytable ORDER BY id DESC LIMIT 1;

但是我收到mysql错误,指出字段列表中的未知列'cumulative_amount',所以我要如何实现输出 请帮助我

预先感谢

1 个答案:

答案 0 :(得分:0)

您可以在下面尝试-

SELECT amount,SUM(amount) OVER(ORDER BY id) AS cumulative_amount,
concat(round((SUM(amount) OVER(ORDER BY id))/amount * 100 ),2),'%') AS percentage
FROM mytable ORDER BY id DESC LIMIT 1