2

我正在努力进行正确的 mysql 查询。这是表格:

**survey_result**
question_id
header_id
answer

其中答案是 (0,1,2,3,4,5) 范围内的 int。我想进行查询,我将计算特定 id 出现了多少次,特定答案发生了。所以对于 question_id = 1 我想看看:

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

而且很可能我想选择一个出现次数最多或最少的答案。但这是第二部分,我正在为第一部分苦苦挣扎。

在第一条语句的巨大帮助下,我设法完成了它,这就是工作版本的样子:

select question_id, 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
4

3 回答 3

2
SELECT
  Question_id,
  answer,
  COUNT(answer)
FROM Questions
WHERE question_id = 1
GROUP BY Question_ID, answer;

对于第二部分,要获得最大出现次数的答案:

SELECT
  Question_id,
  answer,
  COUNT(answer)
FROM questions
GROUP BY Question_ID,  
         answer
HAVING COUNT(answer) = (SELECT MAX(TheCount)
                        FROM
                        (
                           SELECT COUNT(answer) AS TheCount
                           FROM questions
                           GROUP BY answer
                        ) AS t) ;

SQL 小提琴演示

或者:简单地说:

SELECT
  Question_id,
  answer,
  COUNT(answer) Occurrance
FROM Questions
WHERE question_id = 1
GROUP BY Question_ID, answer
ORDER BY Occurrance DESC 
LIMIT 1;

但这只会给你一个值。但是,如果存在具有相同最大出现时间的答案,则使用前一个。

于 2013-02-02T13:15:26.840 回答
1
select question_id, answer, count(*) as occurence_number
from survey_result
group by question_id, answer
order by question_id asc, occurence_number desc;
于 2013-02-02T13:12:08.593 回答
0

SELECT Question_id, answer, COUNT(answer) FROM Questions WHERE = 1 GROUP BY (Question_ID, answer)

于 2013-02-02T14:05:50.923 回答