【问题标题】:SQL/Presto: how to rank within a subgroup of each groupSQL/Presto:如何在每个组的子组内排名
【发布时间】:2023-03-03 03:08:02
【问题描述】:

我有一张如下表:

group_id  sub_group_id   user_id score  time
1          a1            ann      1     2019
1          a1            bob      1     2020
1          a2            cat      0     2020
2          b1            dan      0     2019
2          b1            eva      0     2019
2          b1            ed       1     2020
2          b2            liz      1     2020

我想按分数对每个组的子组中的 user_id 进行排名,然后按时间(越早越好)每个 user_id 获得。所以想要的输出是

group_id  sub_group_id   user_id score   time  rank
1          a1            ann      1      2019  1
1          a1            bob      1      2020  2
1          a2            cat      0      2020  1
2          b1            dan      0      2019  1
2          b1            eva      0      2019  1
2          b1            ed       1      2020  2
2          b2            liz      1      2020  1

【问题讨论】:

    标签: sql data-manipulation presto trino


    【解决方案1】:

    使用rank():

    select t.*,
           rank() over (partition by group_id, sub_group_id order by score desc, time) as ranking
    from t;
    

    实际上,我不确定高分是否比低分更好,所以你可能想要score asc

    【讨论】:

      猜你喜欢
      • 2022-01-11
      • 1970-01-01
      • 2012-08-31
      • 2016-04-28
      • 2021-12-05
      • 2019-05-21
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多