Find the highest number of occurences in a column in SQL

Ronnie picture Ronnie · Jan 8, 2011 · Viewed 8k times · Source

Given this table:

Order
custName description to_char(price)
A desa $14
B desb $14
C desc $21
D desd $65
E dese $21
F desf $78
G desg $14
H desh $21

I am trying to display the whole row where prices have the highest occurances, in this case $14 and $21

I believe there needs to be a subquery. So i started out with this:

select max(count(price))  
from orders  
group by price

which gives me 3.

after some time i didn't think that was helpful. i believe i needed the value 14 and 21 rather the the count so i can put that in the where clause. but I'm stuck how to display that. any help?

UPDATE: So I got it to query the 14 and 21 from this

    select price
    from orders
    group by price
    having (count(price)) in
    (select max(count(price))
    from orders
    group by price)

but i need it to display the custname and description column which i get an error:

select custname, description, price
from orders
group by price
having (count(price)) in
(select max(count(price))
from orders
group by price)

SQL Error: ORA-00979: not a GROUP BY expression

any help on this?

Answer

devio picture devio · Jan 8, 2011

I guess you are pretty close. Since HAVING operates on the GROUPed result set, try

HAVING COUNT(price) IN

or

HAVING COUNT(price) =

replacing your current line.