I have created a sample table here: https://dbfiddle.uk/wUvTIsyN
I am trying to query the most frequently occurring value with group by. Here’s my attempt:
select pid, propName, Address, City, Response, count(Response) as cr
from Prop
group by
pid,
propName,
Address,
City,
Response
order by
cr
limit 1;
Expected output:
pid propName Address City Response
1 p1 addr1 c1 2
2 p2 addr2 c2 3
2
and 3
are most frequently occurring responses.
2
Answers
You should only group by the column whose frequency you want to get.
You shouldn’t include other columns in the
SELECT
list, since they’re different for rows with the same response.If you want to see the rows that have that response, you can join the table with this subquery.
yeah, so I created a an intermediate table res which groups just the way you did it and stores the count of it, then gets the maximum and then equates which one of these tuples have a count=maximum? those tuples(excluding the count) get displayed.
go through the fiddle, it shall be clear:-
https://dbfiddle.uk/f9TTCN9X
AND I have shown all those tuples which have the highest frequency… I think that’s what you meant… Please clarify your question if this was not the intended answer.
My 1st query creates the intermediate table res:-
My 2nd query does the job:-