1

我已经解决了一个问题并遇到了另一个问题。基本上我想选择 question_id、答案和最大出现次数。我从收集问题和答案的基本表运行我的查询(问题 id 代表问题,答案代表从 0 到 5 的答案,对应于其他表,但没关系)。

**survey_result**
question_id
answer (int from 0 to 5)

样本调查结果:

question_id answer
1           3
1           5
1           2
2           2
2           0
2           4

这是查询,其目的是检查每个问题,哪个答案(从 0 到 5)出现次数最多。

select question_id, answer, max(occurence_number) FROM
(select question_id, answer, count(*) as occurence_number
from survey_result
group by question_id, answer
order by question_id asc, occurence_number desc) as results
GROUP BY question_id

所以一个子查询会产生这样的结果:

question_id answer occurence_number
1           0      12
1           1      20
1           2      34
1           3      5
1           4      9
1           5      15

但主要查询结果是这样的:

question_id answer occurence_number
1           0      12
2           0      20
3           0      34
4           0      5

所以问题是它总是显示答案 0,我想得到正确的答案号码。

4

2 回答 2

2

遗憾的是,由于 MySQL 缺少WITH声明,这有点多余,但这应该可以满足您的需求。如果出现平局,它将返回更高的答案。

SELECT s1.question_id, MAX(s1.answer) answer, MAX(s1.c) occurrences
FROM
   (SELECT question_id, answer, COUNT(*) c 
    FROM survey_result GROUP BY question_id,answer) s1
LEFT JOIN
   (SELECT question_id, answer, COUNT(*) c
    FROM survey_result GROUP BY question_id,answer) s2
  ON s1.question_id=s2.question_id
 AND s1.c < s2.c
WHERE s2.c IS NULL
GROUP BY question_id

一个可以玩的 SQLfiddle

于 2013-02-02T16:07:23.190 回答
0

我认为你过于复杂了,试试这个:

select question_id, answer, count(*) as occurence_number
from survey_result
group by question_id, answer
于 2013-02-02T15:59:29.640 回答