Oracle11g 获取具有相同密钥的不同记录数

Oracle11g 获取具有相同密钥的不同记录数,oracle11g,Oracle11g,假设我有一个表a: 我想获得具有相同B_ID的最大数量的不同记录,我还想知道B_ID在哪里发生。在这个例子中,我想得到值3和26 实现这一点的最佳方法是什么?最佳方法是简单的聚合+排序+限制返回的行数为1: select b_id, no_of_records from ( select b_id, count(1) as no_of_records from table_A group by b_id order by no_of_records desc )

假设我有一个表a:

我想获得具有相同B_ID的最大数量的不同记录,我还想知道B_ID在哪里发生。在这个例子中,我想得到值3和26


实现这一点的最佳方法是什么?

最佳方法是简单的聚合+排序+限制返回的行数为1:

select b_id, no_of_records
from (
    select b_id, count(1) as no_of_records
    from table_A
    group by b_id
    order by no_of_records desc
)
where rownum <= 1;
当然,即使您有多个具有相同最高记录数的组,也会返回1行。如果您希望所有组具有相同的最高记录数,那么方法略有不同

select b_id, no_of_records
from (
    select b_id, count(1) as no_of_records,
        rank() over (partition by null order by count(1) desc) as rank$
    from table_A
    group by b_id
)
where rank$ <= 1;
select b_id, no_of_records
from (
    select b_id, count(1) as no_of_records,
        rank() over (partition by null order by count(1) desc) as rank$
    from table_A
    group by b_id
)
where rank$ <= 1;