在SQL中查找列中出现的最大次数

时间:2011-01-08 19:51:01

标签: sql oracle ora-00979

鉴于此表:

订单
custName描述to_char(价格)
一个desa $ 14
B desb $ 14
C desc $ 21
D desd $ 65
E dese $ 21
F desf $ 78
G desg $ 14
H desh $ 21

我试图显示价格最高的整行,在这种情况下为14美元和21美元

我认为需要有一个子查询。所以我从这开始:

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

给了我3。

经过一段时间后,我认为这没有用。我相信我需要值14和21而不是计数,所以我可以把它放在where子句中。但是我发现了如何显示它。有什么帮助吗?

更新:所以我让它从这个

查询14和21
    select price
    from orders
    group by price
    having (count(price)) in
    (select max(count(price))
    from orders
    group by price)

但是我需要它来显示我得到错误的custname和description列:

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

对此有何帮助?

4 个答案:

答案 0 :(得分:1)

我猜你很亲密。由于HAVING在GROUPed结果集上运行,请尝试

HAVING COUNT(price) IN

HAVING COUNT(price) =

替换当前行。

答案 1 :(得分:0)

由于您将问题标记为oracle,因此您可以使用windowing functions在同一查询中获取聚合和详细数据。

SELECT   COUNT (price) OVER (PARTITION BY price) count_at_this_price, 
         o.* 
from orders o 
order by 1 desc

答案 2 :(得分:0)

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
)
);

Reference

答案 3 :(得分:-1)

您可以尝试类似

的内容
select * from orders where price in (select top 2 price from orders group by price order by price desc)

我不确定在Oracle中限制结果,在SQL Server中是顶级的,也许你应该使用限制。