根据mysql中的另一列获取百分比列

时间:2018-03-06 04:29:44

标签: mysql sql database

我的付款表如下所示:

+--------------+---------+
| Type         | Amount  |
+--------------+---------+
| General      | 500     |
| General      | 700     |
| Assets       | 450     |
| Business     | 270     |
| General      | 70      |
| Assets       | 350     |
+--------------+---------+

我希望按类型输入总和和百分比。

我的查询是 -

SELECT fld_type, SUM(fld_amount) FROM tbl_payment group by fld_type


+--------------+---------+
| Type         | Amount  |
+--------------+---------+
| General      | 1270    |
| Assets       | 800     |
| Business     | 270     | 
+--------------+---------+

我只是得到了总和,但是不能用这个案例2340中的金额总和计算百分比,并且用每个组项目计算,例如一般 -

1270 * 100/2340 = 56.27

像这样 -

+--------------+---------+----------+
| Type         | Amount  | Percent% |
+--------------+---------+----------+
| General      | 1270    |   54.27  |
| Assets       | 800     |   34.19  |
| Business     | 270     |   11.54  |
+--------------+---------+----------+

感谢任何帮助。

2 个答案:

答案 0 :(得分:1)

要获得每组的百分比,您可以这样做

select fld_type, 
sum(fld_amount),
(sum(fld_amount) / t.total) * 100 percent
from tbl_payment 
cross join (
select sum(fld_amount) total from tbl_payment
) t
group by fld_type

Demo

答案 1 :(得分:1)

试试这句话

SELECT type,sum(amount),sum(amount)*100/(select sum(amount) from tbl_payment) FROM `tbl_payment` group by type