选择最大值出现的id和值

时间:2013-02-02 15:35:48

标签: mysql select max

我已经解决了一个问题并遇到了另一个问题。 Basicaly我想选择question_id,answer和最大出现次数。我从基本表中运行我的查询,收集问题和答案(问题ID表示问题和答案代表从0到5的答案,对应于其他表,但这无关紧要。)

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

样本survey_result:

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,我想得到正确的答案号。

2 个答案:

答案 0 :(得分: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

An SQLfiddle to play with

答案 1 :(得分:0)

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

select question_id, answer, count(*) as occurence_number
from survey_result
group by question_id, answer