【问题标题】:For each category (A field), I would like the top ten types (another field) by count对于每个类别(A 字段),我想要按计数排名前十的类型(另一个字段)
【发布时间】:2017-11-28 09:22:45
【问题描述】:

假设我有一张如下所示的表格:

+------------+-------------+-------+
|  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 方式来执行此操作。有吗?

【问题讨论】:

标签: sql postgresql


【解决方案1】:
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 个结果“有关系”,请使用 rank() 函数而不是 row_number()

【讨论】:

【解决方案2】:

U可以使用rank、row number和dense_rank

Link to dense rank and rank description

row_number

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-29
    • 1970-01-01
    • 2019-06-28
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    相关资源
    最近更新 更多