How to do the math in sql query to calculate percentage difference?

I would like to conduct surveys (2 or more options) and put the results in a table. I just want to know how I could count the results in a sql query.

Even more, should I do the math in the query or just use PHP to do the math?

Example

Table of questions

question_id (int) question (text) answer_1 (varchar) answer_2 (varchar) answer_3 (varchar) etc... 

Answer Table

 answer_id (int) question_id (int) answer (int) The answer they chose. (1, 2, 3, etc.) 

How should I / I calculate the results?

Edit: using MySQL, PHP. The difference between the answers (45% said blah, 50% said blah blah, 5% said they were flea). Not for homework, Im EE, not CS

+3
math sql php mysql
source share
3 answers

If the number of answers is not known in advance, it would be easier to divide the question table into 2 - one for questions (question_id, question_text) and one for choice (question_id, choice_id, choice_text). An answer table can be executed (question_id, answer_id, choice_id). Then, choosing it, something like the following will be used (QID = identifier of the question you are choosing):

 SELECT choice, (COUNT(*) / (SELECT COUNT(*) FROM answers WHERE answers.question_id = QID)) * 100 AS percentage FROM choices INNER JOIN answers ON choices.choice_id = answers.choice_id AND choices.question_id AND choices.question_id WHERE choices.question_id = QID GROUP BY choice_id; 

All this means that the total number of answers in the internal query, and then for each choice, divide the number of answers with this choice compared to the total.

+1
source share

This will allow you to choose the popularity of each answer in the question:

 SELECT question, COUNT(*) / ( SELECT COUNT(*) FROM answers ai WHERE ai.question = a.question ) FROM answers a GROUP BY question, answer 

It will not select answers if they have never been given.

0
source share
 select answer, count(*) from Answers where answer_id = 1 group by answer 

or

 select answer_id,answer, count(*) from Answers group by answer_id, answer 

I would give you a request that takes into account the answers to each question, but, unfortunately, you have no way to link the answers to the questions. Neither do you need to answer answer_1, answer_2, etc. In the table of questions. You need to normalize the table. If you do not understand how to do this, you need to learn before designing a database.

0
source share

All Articles