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

时间:2015-11-06 08:00:18

标签: oracle11g

我们假设我有一张桌子A:

# Select the word directly
random_word = random.choice(list(dict_of_strings.values()))
# Or select the key, and then access the word
random_word_index = random.choice(list(dict_of_strings.keys()))
random_word = dict_of_strings[random_word_index]

# As Pynchia pointed out, you can simply do the following without the
# need to fetch the keys, and cast them to a list.
# This will work on Python 3.5+, but not Python 3.4< or Python 2.7<
# in such case, you must make your keys start from zero, not one
random_word = random.choice(dict_of_strings)

我想获得具有相同| ID | B_ID | C | column 1 | ... | column x| | 1 | 24 | 44 | xxxxxxx | 2 | 25 | 55 | xxxxxxx | 3 | 25 | 66 | xxxxxxx (data in all other columns are the same) | 4 | 26 | 77 | xxxxxxx | 4 | 26 | 78 | xxxxxxx | 4 | 26 | 79 | xxxxxxx 的最高数量的不同记录(我也想知道发生这种情况的B_ID)。所以在这个例子中我想得到值3和26。

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

1 个答案:

答案 0 :(得分:0)

最好的方法是简单的聚合+排序+限制返回的行数为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;