按组计算 SQL 中的百分比 [英] CALCULATE PERCENTAGE IN SQL by group
本文介绍了按组计算 SQL 中的百分比的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从这样的数据库中提取数据(为简单起见而简化),我想添加一个名为百分比"的列.
I pulled out data from a database like this (simplified for the sake of simplicity), I'd like to add a column called "percentage".
ID GRADE PERCENTAGE
1 10 10/(10+20) * 100 -- THIS PART SHOULD BE SHOWN IN DIGIT
1 20 .
2 15 15/(15+24+16) * 100
2 24
2 16
3 29
4 96
4 159
. .
. .
. .
先谢谢你
推荐答案
内部选择获取 id
的 garde
和.
The inner select gets the garde
sum of the id
s.
select t.id, t.grade, t.grade * 100 / gsum
from your_table t
join
(
select id, sum(grade) as gsum
from your_table
group by id
) tmp on tmp.id = t.id
这篇关于按组计算 SQL 中的百分比的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文