2009-04-27 25 views
0

這是指我之前問過的問題,並且得到了一個非常快速的答案(max count together in an sql query)。該問題類似,但前提問題中的解決方案會迫使我在循環中訪問數據庫,這會導致性能問題。所以現在我有一些加入後:在SQL查詢中一起計算最大值2

id | description 
    0 | bla 
    0 | blub 
    0 | bla 
    1 | blablub 
    1 | bla 
    ... | ... 

正如你可以看到,現在的id不是主鍵了。我想要的是獲得結果集中每個id最常用的描述。它應該看起來像這樣:

id | most_popular_description | times_the_desc_appeared_for_an_id 
    0 |      bla |         2 
    1 |     blablub |         1 
... |      ... |        ... 

回答

1

如果你只想要最流行的項目,那麼我相信這應該會給你你要找的結果集。還有其他方法可以做到這一點,但stats_mode是獲得組中「最流行」值最簡單的方法(即模式)。

SELECT t.id, 
     t.description AS most_popular_description, 
     COUNT(*) AS times_the_desc_appeared_for_an_id 
FROM mytable t INNER JOIN (
    SELECT id, stats_mode(description) AS desc FROM mytable GROUP BY id 
) a ON t.id = a.id AND t.description = a.desc 
GROUP BY t.id, t.description; 

請注意,嵌套查詢(內聯視圖)是必要的,因爲您還需要計數。

+0

非常酷,非常感謝 – Red33mer 2009-05-01 05:37:12

1

這應該有所斬斷。

select id, description, COUNT(description) 
from mytable 
group by id, description 
order by 3 desc 
+0

SRY基因,但它並不完全是我想要的,還是感謝幫助 – Red33mer 2009-05-01 05:36:53

0

我想你可以使用dense_rank()分析函數來獲取每個組集的前N個。

事情是這樣的:

select id, description, times_the_desc_appeared_for_an_id 
from 
(
    select id, description, count(description) times_the_desc_appeared_for_an_id 
    dense_rank() over (partition by id, description order by count(description) desc) position 
    from mytable 
    group by id, description 
) 
where 
    position <= 3 
order by id, times_the_desc_appeared_for_an_id; 
+0

還沒有測試它,因爲通過rwwilden工程解決方案,但還是謝謝你 – Red33mer 2009-05-12 20:30:21