【问题标题】:AVG on same column by values in another column single sql queryAVG 在同一列上按另一列单个 sql 查询中的值
【发布时间】:2012-01-12 13:01:05
【问题描述】:

我想通过不同列单个sql查询中的值在同一列上查找AVG。

table - question_rating
review_id
question_id
rating
  • 每条评论有多个 16 个问题和评分。
  • question_id 值为 1 到 16。
  • 评分值从 1 到 5。

我想找到一组问题的平均值

期望的输出-

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 等找到此类输出的任何简单方法。

【问题讨论】:

  • 我不明白“我想通过不同列单个 sql 查询中的值在同一列上查找 AVG”是什么意思。意思是。

标签: php mysql sql average


【解决方案1】:

你应该做一张桌子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

【讨论】:

  • @SomnathMuluk - 你明确指出,例如,“第 1 组”由问题 (1,3) 组成。这个答案建议将该关联放入另一个表中,加入它并使用 GROUP BY。除非您没有解释有关您的数据的某些内容,否则这确实有效。
【解决方案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

【讨论】:

  • 它给出的错误是“您的 SQL 语法有错误;请检查与您的 MySQL 服务器版本相对应的手册,以获取在 'WHEN question_id IN (1,2) THEN 附近使用的正确语法'g1' "
  • @OlegDok CASE sintax 是CASE WHEN question=1 THEN result
  • @FlorinGhita 两者兼有,见:dev.mysql.com/doc/refman/5.6/en/case-statement.html
  • 我认为是这样的:(从案例表达式读取)The return type of a CASE expression is the compatible aggregated type of all return values, but also depends on the context in which it is used. If used in a string context, the result is returned as a string. If used in a numeric context, the result is returned as a decimal, real, or integer value.
  • @FlorinGhita g1、g2 和其他人吃了相当的 8-)
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 2021-10-24
  • 2012-03-16
  • 1970-01-01
  • 1970-01-01
  • 2017-01-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多