假设我有一张如下表:
+------------+-------------+-------+
| 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 |
+------------+-------------+-------+
对于每个类别,我都希望计算前十种类型。
鉴于有问题的表实际上是数百万行,如果我只是做了select category, type, sum(Count) group by category, type order by category, type
那么我会得到类型不在前十名的结果。
我正在使用postgresql,但相信可能有一种更“通用”的SQL方式。有吗?
答案 0 :(得分: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
这为每个Category
提供了10行(如果存在),最高Count
列。
如果您想获得前10名结果&#34;有关系&#34;,请使用rank()
函数代替row_number()
答案 1 :(得分:0)