SQL calculates the percentage of two values ​​with the same sub_id.

I am working on a project in which I list 5 problems with 2 solutions each. Users can vote on one solution per problem. Now I have to calculate the percentage of the highest value for each problem.

For example, in problem 1, I have 20 votes for solution 1 and 30 votes for solution 2, I want to get 60%. I know that I will need to count the two voting values ​​together for each division of the problem by 100, and then multiply by the value that is the highest.

How to do this in my dao (with sql)? Do I have to make another column in the “solutions” table?

table: solutions
+----------+------------+---------+
|    id    | id_problem |  vote   |
+----------+------------+---------+
|    1     |     1      |    25   |
|    2     |     1      |    10   |
|    3     |     2      |    18   |
|    4     |     2      |    2    |
|    5     |     3      |    6    |
|    6     |     3      |    7    |
|    7     |     4      |    11   |
|    8     |     4      |    4    |
|    9     |     5      |    5    |
|    10    |     5      |    2    |
+----------+------------+---------+
+4
source share
1

:

select 
    id_problem,
    CONCAT(ROUND(MAX(vote) / SUM(vote), 2) * 100, '%') as Percentage
from solutions
group by id_problem;
+2

All Articles