2017-06-25 2 views
0

で上位10種類の(別のフィールドを)希望:各カテゴリについては各カテゴリ(分野)のために、私はのは、私はこのようになりますテーブルがあるとしましょう、カウント

+------------+-------------+-------+ 
| Category | Type  | Count | 
+------------+-------------+-------+ 
| Fruits  | Apple  | 13 | 
| Vegetables | Carrot  |  7 | 
| Legumes | Kidney Bean |  1 | 
| Fruits  | Orange  |  1 | 
| Vegetables | Green  |  3 | 
| Legumes | Black Bean |  1 | 
| Vegetables | Leek  |  1 | 
| Fruits  | Banana  |  1 | 
| Legumes | Lentil  |  1 | 
| Fruits  | Mango  |  1 | 
| Fruits  | Pinapple | 18 | 
| Fruits  | Strawberry |  1 | 
| Legumes | Flat Bean |  2 | 
| Vegetables | Brocolli |  8 | 
| Fruits  | Rambotan |  1 | 
| Fruits  | Marang  | 15 | 
| Vegetables | Cauliflower |  5 | 
| Vegetables | Aubergine |  1 | 
+------------+-------------+-------+ 

、私は希望しますカウントで上位10種類。

問題のテーブルが実際には何百万行もある場合、私が単にselect category, type, sum(Count) group by category, type order by category, typeを実行した場合、そのタイプがトップ10にない結果が得られます。

私はpostgresqlを使用していますが、これを行うための「一般的な」SQLの方法があると思われます。ある?

+0

チェックこれをDENSE_RANKすることができます - https://spin.atomicobject.com/2016/03/12/select-top-n-per-group-postgresql/ – tom

答えて

4
select Category, Type, Count from (
    select your_table.*, row_number() over(partition by Category order by Count desc) as rn 
    from your_table 
) t 
where rn <= 10 

これは最高Countカラムで、各Categoryために(存在する場合)、正確に10行を与えます。あなたは、その後、代わりにrank()機能を使用する "タイで" トップ10の結果をしたい場合は

row_number()

+0

あなたの答えを説明してください –

+0

ちょっと働いて!どうもありがとうございました。何が終わったのですか?(パーティションは何をしていますか? –

+1

@DougFir - うれしいことですが、ここではウィンドウ関数の説明です。https://www.postgresql.org/docs/current/static/tutorial-window.html –

関連する問題