我希望通过不同列的单个sql查询中的值在同一列上找到AVG。
table - question_rating
review_id
question_id
rating
我希望找到平均一组问题
期望的输出 -
qustion_id rating
-------------------------
g1 4.4
g2 3.7
g3 5.6
g1是一组问题(1,3) g2是一组问题(2,6) g3是一组问题(7,8) .... G8
伪代码 -
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
我知道可以通过单独查询来完成,但我想通过单一查询来了解。
或者通过php等找到这样的输出的任何简单方法
答案 0 :(得分:3)
你应该制作一个表question_groups
question_id group_id
q1 g1
q2 g2
q3 g1
q4 g3
q5 g3
q6 g2
选择将是
select group_id, avg(rating)
from question_rating a
join question_groups b on (a.question_id= b.question_id)
group by group_id
答案 1 :(得分:2)
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