简体   繁体   English

MySQL多列求和的平均值

[英]Mysql Average of Sum of multiple columns

I have a mysql query to build that is giving me a little trouble. 我有一个要构建的mysql查询,这给我带来了一些麻烦。 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. 我有一个调查答案表,其中有5列,用于回答5个问题。 The questions are always from 1(lowest) to 5(highest). 问题总是从1(最低)到5(最高)。

I need to find the average of all 5 answers and display as a percentage out of 100%. 我需要找到所有5个答案的平均值,并显示为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. 上面的查询不起作用,我知道sum对该列名称的所有行进行计数。 Is there MySQL syntax to add up multiple columns of the same entry? 是否存在MySQL语法来添加同一条目的多个列? Also, if there is, may I divide that sum by a number I choose, then average those results in one query?? 另外,如果有,我可以将该总和除以我选择的数字,然后将这些结果平均一次查询?

Thank you. 谢谢。 Jason 贾森

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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