1

I have a mysql query to build that is giving me a little trouble. I have completed what I need with a slew of queries put together, but I know there must be a better way.

I have a survey answer table, with 5 columns for answers to 5 questions. The questions are always from 1(lowest) to 5(highest).

I need to find the average of all 5 answers and display as a percentage out of 100%.

At first, I accomplished this by:

Select qone,qtwo,qthree,qfour,qfive FROM survey_answers WHERE survey_id='$survey_id'

Then as I loop through all answers:

$counter++;
$survey_total = $survey_total+(($qone+$qtwo+$qthree+$qfour+$qfive)/25);

Finally, after looping through all survey results:

$total_average = $survey_total/$counter;

So this is how I solve what I need to do.

Can anyone help me refine this query, maybe even into one?

Is it possible to do something like:

Select AVG(SUM(qone+qtwo+qthree+qfour+qfive)/25)) FROM survey_answers WHERE survey_id='$survey_id'

The above query does not work, and I know sum counts all rows of that column name. Is there MySQL syntax to add up multiple columns of the same entry? Also, if there is, may I divide that sum by a number I choose, then average those results in one query??

Thank you. Jason

1 Answer 1

1

Try something like this, that should give you the result you're looking for in %

SELECT 
 20 * q1 / devider AS Question1, 
 20 * q2 / devider AS Question2, 
 20 * q3 / devider AS Question3, 
 20 * q4 / devider AS Question4, 
 20 * q5 / devider AS Question5
FROM (
 SELECT (
  SELECT COUNT( survey_id ) 
   FROM (
    SELECT survey_id
    FROM `survey_answers`
    WHERE  `survey_id` ='$survey_id'
    )tt1
   ) AS devider, SUM(`qone') AS q1, SUM(`qtwo`) as q2, SUM(`qthree`) as q3, SUM(`qfour`) as q4, SUM(`qfive`) AS q5
   FROM  `survey_answers` 
   WHERE  `survey_id` ='$survey_id'
   GROUP BY  `survey_id`
  )tt2
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.