MYSQL calculate the chosen percentage

Asked

Viewed 6,721 times

3

I’m doing a QUIZ and at a certain point I have to show the percentage of alternatives chosen by users. I have this table:

ID RESPOSTA
1  a
2  a
3  b
4  b
5  c
6  a

The answer I need from MYSQL would be the percentages of choice:

a - 50% b - 33,33% c - 16,6%

How to do this? I tried with GROUP BY, but did not roll, any suggestions?

1 answer

6


I don’t know if it would be the best way to do it, but I would do it like this:

SELECT count(q.id) / t.total * 100 as perc, resposta from quiz q,
( SELECT count(*) as total from quiz ) t
GROUP BY q.resposta
  • Hey, it’s all right. But when I put a WHERE, to choose only the chosen alternative of an error question: $sql = $Pdo->prepare('SELECT Count(q. id) / t.total * 100 as Perc, q.resposta FROM quiz_resposta q, (SELECT Count(*) as total FROM quiz_resposta) t GROUP BY q.resposta WHERE q.idquestion = :question');

  • Where comes before group by

  • exact, Where must be inserted before the group by

  • In total subselect you must also have Where, otherwise it will bring the total of all questions, I think it would look like this: $sql = $Pdo->prepare('SELECTS T Count(q. id) / t.total * 100 as Perc, q.reply FROM quiz_answer q, (SELECT Count(*) as total FROM quiz_answer WHERE idquestion = :question) t WHERE q.idquestion = :question GROUP BY q.answer');

  • Thanks, straight and fast the consultation.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.