我正在努力制作一个合适的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
答案 0 :(得分: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) ;
或:简单地说:
SELECT
Question_id,
answer,
COUNT(answer) Occurrance
FROM Questions
WHERE question_id = 1
GROUP BY Question_ID, answer
ORDER BY Occurrance DESC
LIMIT 1;
但这只会给你一个价值。 然而,如果有相同最大出现次数的答案,请使用前一个。
答案 1 :(得分: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;
答案 2 :(得分:0)
选择 Question_id, 回答, COUNT(答案) 来自问题 WHERE = 1 GROUP BY(Question_ID,answer)