SQL 排名和顺序

SQL Rank and Order

我正在处理一个数据集,在该数据集中,我希望为每个 class_rk 以 driver SKU 销售的商品获得排名第一的卖家,然后在每个 class_rk,等等。Class_rk(与 sold_sku 关联)已在先前的查询中识别。这是数据集:

 driver_sku sold_sku    class_rk    sold_units
 555        432           1         20
 555        235           2         17
 555        322           2         15
 555        253           1         14
 555        152           3         13
 555        732           1          9
 555        913           3          6

我要寻找的输出:

 driver_sku sold_sku    class_rk    sold_units
 555        432           1         20
 555        235           2         17
 555        152           3         13
 555        253           1         14
 555        322           2         15
 555        913           3          6
 555        732           1          9

这是我迄今为止尝试过的代码:

 select driver_sku, sold_sku, class_rk, sold_count,
 row_number() over(partition by driver_item_id order by class_rk, sold_count  desc) as rank from data_table;

根据您对问题的描述,您似乎想按 class_rk:

进行分区
select driver_sku, sold_sku, class_rk, sold_count,
       row_number() over(partition by driver_item_id, class_rk
                         order by sold_count desc
                        ) as rank
from data_table;

然而,这并不符合预期的结果。

编辑:

根据您描述问题的方式,您似乎想按 class_rk 分区并更改 order by:

select t.*
from (select driver_sku, sold_sku, class_rk, sold_count,
             row_number() over (partition by driver_item_id, class_rk
                                order by sold_count desc
                               ) as rank
      from data_table
     ) t
order by rank, class_rk

如果你真的想枚举它们:

select t.*,
       row_number() over (partition by driver_sku, rank
                          order by sold_count desc) as newcol
from (select driver_sku, sold_sku, class_rk, sold_count,
             row_number() over (partition by driver_item_id, class_rk
                                order by sold_count desc
                               ) as rank
      from data_table
     ) t
order by rank, class_rk

根据您的评论,您似乎只想要每个 class_rk 的记录。我想这可能是您要找的:

SELECT driver_sku, sold_sku, class_rk, max(sold_count)
FROM <TABLE>
GROUP BY driver_sku, class_rk
ORDER_BY class_rk

但是,如果您希望顺序与问题中的一样,我认为您必须这样做:

with ranked as (
    SELECT driver_sku, sold_sku, class_rk, sold_count,
        row_number() over(partition by driver_sku, class_rk order by sold_count desc) as rank
    FROM <TABLE>    
)

SELECT driver_sku, sold_sku, class_rk, sold_count
FROM ranked
GROUP BY driver_sku, rank
ORDER BY class_rk