【问题标题】:Find the highest number of occurences in a column in SQL在 SQL 中查找列中出现次数最多的
【发布时间】:2011-06-05 20:49:27
【问题描述】:

鉴于此表:

订购
custName 描述 to_char(price)
德萨 $14
14 美元
C 描述 $21
D 最低价 $65
21 美元
F DESF 78 美元
G 设计 $14
H 德什 $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)

但我需要它来显示我收到错误的客户名称和描述列:

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

有什么帮助吗?

【问题讨论】:

  • 看看我的回答
  • 您的回答是否对我最初的问题或更新问题有帮助?我尝试使用你的,但我也遇到了一些错误

标签: sql oracle ora-00979


【解决方案1】:

我猜你很接近。由于 HAVING 对 GROUPed 结果集进行操作,请尝试

HAVING COUNT(price) IN

HAVING COUNT(price) =

替换当前行。

【讨论】:

  • 我搞砸了它并得到了同样的东西。不过谢谢!
【解决方案2】:

你可以试试

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

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

【讨论】:

  • 这是家庭作业,我还没有学习过顶级功能(但对未来有帮助),所以我认为我不能使用它。不过谢谢!
  • TOP 在 Oracle 中不可用。它在 SQL Server 和其他一些数据库中可用
【解决方案3】:

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

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

【讨论】:

    【解决方案4】:
    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

    【讨论】:

      猜你喜欢
      • 2020-07-22
      • 2019-10-27
      • 2013-07-14
      • 2021-06-11
      • 2011-04-29
      • 1970-01-01
      • 2016-01-16
      • 2018-05-08
      • 2020-04-19
      相关资源
      最近更新 更多