I’m struggling with making a proper mysql query. Here’s the table:
**survey_result**
question_id
header_id
answer
Where answer is int in (0,1,2,3,4,5) range. I’d like to make a query, where i will count how many times for specific id, a specific answer occurred. So for question_id = 1 i’d like to see:
question_id answer occurence_number
1 0 12
1 1 20
1 2 34
1 3 5
1 4 9
1 5 15
And most likely i’d like to pick an answer with either most or least occurrences. But that’s the second part, i’m struggling with first one.
With huge help with first statement i managed to finish it off, this is how working version looks:
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
For the second part, to get the answer with the max occurrence number:
SQL Fiddle Demo
Or: Simply:
But this will give you only one value. However, if there are answers with the same max occurrence times use the previous one.