Nayana Nayana - 3 months ago 18
MySQL Question

CALCULATE PERCENTAGE IN SQL by group

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
. .
. .
. .


thank you in advance

Answer

The inner select gets the garde sum of the ids.

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
Comments