Find the highest number of occurences in a column in SQL
Question
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?
Solution
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.
OTHER TIPS
Since you tagged the question as oracle, you can use windowing functions to get aggregate and detail data within the same query.
SELECT COUNT (price) OVER (PARTITION BY price) count_at_this_price,
o.*
from orders o
order by 1 desc
select employee, count(employee)
from work
group by employee
having count(employee) =
( select max(cnt) from
( select employee, count(employee cnt
from work
group by employee
)
);
You could try something like
select * from orders where price in (select top 2 price from orders group by price order by price desc)
I'm not sure of limiting results in Oracle, in SQL Server is top, maybe you should use limit.