2015-11-06 69 views
-2

假設我有一個表答:

獲取的不重複的記錄數以相同的密鑰

| 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重複的記錄數量最多(我也想知道B_ID如果這發生)。所以在這個例子中,我想得到值3和26.

什麼是最好的方法來實現這一目標?

回答

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;