简体   繁体   中英

SQL calculate percentage of two values with same sub_id.

I'm working on a project where I list 5 problems with 2 solutions each. The users can vote on one solution per problem. Now I have to calculate the percentage of the highest value per problem.

For example in problem 1 I have 20 votes on solution 1 and 30 votes on solution 2, I want to get 60%. I know I will have to count the two vote values together per problem divide by 100 and then multiply by the value that is the highest.

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

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

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM