sql多查询

jjhzyzn0  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(304)

我有这种情况:

select AVG(t_vote.rating) as AVG_1 from t_vote  
INNER JOIN t_question.c_question = t_vote.c_question 
where t_question.aspect_code = 'A';

select AVG(t_vote.rating) as AVG_2 from t_vote  
INNER JOIN t_question.c_question = t_vote.c_question 
where t_question.aspect_code = 'B';

select AVG(t_vote.rating) as AVG_3 from t_vote  
INNER JOIN t_question.c_question = t_vote.c_question 
where t_question.aspect_code = 'C';

有没有可能在一个查询中用3个不同的where子句得到这3个不同的值?
这是我的table结构,如果我弄错了table,请纠正我
我把这个表作为一个例子,但我的表实际上看起来像这个表的例子

shstlldc

shstlldc1#

可以使用条件聚合:

SELECT 
  CASE WHEN t_question.aspect_code = 'A' THEN AVG(t_vote.rating) END AS AVG_1,
  CASE WHEN t_question.aspect_code = 'B' THEN AVG(t_vote.rating) END AS AVG_2, 
  CASE WHEN t_question.aspect_code = 'C' THEN AVG(t_vote.rating) END AS AVG_3 
FROM t_vote 
JOIN t_question 
  ON t_question.c_question = t_vote.c_question AND 
     t_question.aspect_code IN ('A', 'B', 'C');

相关问题