简体   繁体   English

在同一列上通过另一列SQL查询中的值进行AVG

[英]AVG on same column by values in another column single sql query

I want to find AVG on same column by values in different column single sql query. 我想通过不同列单个sql查询中的值在同一列上找到AVG。

table - question_rating
review_id
question_id
rating
  • for each review there are multiple 16 questions and ratings. 每个评论有16个问题和等级。
  • question_id values are 1 to 16. question_id的值是1到16。
  • rating values are from 1 to 5. 评分值为1到5。

I want to find avg of group of questions as 我想查找一组问题的平均值

Desired output- 期望的输出

qustion_id     rating
-------------------------
g1               4.4
g2               3.7
g3               5.6

g1 is group of questions (1,3) g2 is group of questions (2,6) g3 is group of questions (7,8) ....g8 g1是一组问题(1,3)g2是一组问题(2,6)g3是一组问题(7,8).... g8

pseudo code- 伪代码

 select (if(qustion=1 and question=3) as g1,
if(qustion=2 and question=6) as g2), ..
)avg(rating of respective group) from question_rating

I know it can be done by taking query separately but I want to know by single query. 我知道可以通过单独进行查询来完成,但是我想通过单个查询来知道。

Or any easy way to find such output by php,etc. 或通过php等找到此类输出的任何简便方法。

You should make a table question_groups 您应该创建一个表question_groups

question_id  group_id
q1          g1
q2          g2
q3          g1
q4          g3
q5          g3
q6          g2

And the select will be 选择将是

select group_id, avg(rating)
from question_rating a
  join question_groups b on (a.question_id= b.question_id)
group by group_id
SELECT
  CASE question_id 
  WHEN 1 THEN 'g1'
  WHEN 3 THEN 'g1'
  WHEN 2 THEN 'g2'
  WHEN 4 THEN 'g2'
  ELSE 'others' END AS qGroup,
  AVG(rating) AS AvgRating
FROM question_rating
GROUP BY 
  CASE question_id 
  WHEN 1 THEN 'g1'
  WHEN 3 THEN 'g1'
  WHEN 2 THEN 'g2'
  WHEN 4 THEN 'g2'
  ELSE 'others' END

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

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