MySQL简单实现分组排序(类似row_number over (partition by ...))

  • 原始数据


    MySQL简单实现分组排序(类似row_number over (partition by ...))_第1张图片
    原始数据
  • 需求内容

原始数据增加一列,为球员最高分在自己所属分区排名!

  • 分组排序
SELECT A.area "分区",
       A.player_name "运动员名",
       A.highest_score "最高分",
       SUM(CASE WHEN A.area = B.area AND A.highest_score < B.highest_score THEN 1
                WHEN A.area = B.area AND A.highest_score = B.highest_score AND SHA(A.player_name) <= SHA(B.player_name) THEN 1
                ELSE 0 END )  "分区排序"    
FROM NBA_PLAYER A LEFT JOIN NBA_PLAYER B 
                  ON 1 = 1
GROUP BY A.area,A.highest_score,A.player_name
ORDER BY 1,4
MySQL简单实现分组排序(类似row_number over (partition by ...))_第2张图片
分组排序后数据
  • 注意

----- 这样只按照某一字段排序,值一样的数据会按照大的顺序作为序号,比如两个第2名序号都是3,没有序号2的,例如上面如果这样写就没有第二名了!
SUM(CASE WHEN A.area = B.area AND A.highest_score <= B.highest_score THEN 1 ELSE 0 END ) "分区排序"

----- 我们可以增加一个第二排序,例如上面的例子!
SUM(CASE WHEN A.area = B.area AND A.highest_score < B.highest_score THEN 1 WHEN A.area = B.area AND A.highest_score = B.highest_score AND SHA(A.player_name) <= SHA(B.player_name) THEN 1 ELSE 0 END ) "分区排序"

  • 思路解析

通过自身关联笛卡尔积,然后拿每条数据依次和所有数据比较,用case when 判断条件找到我们想要的结果!

这个思路也可以解决累计求和类似问题,比如销售金额,要求每天数据加上一列,截止到当天的销售金额之和!

你可能感兴趣的:(MySQL简单实现分组排序(类似row_number over (partition by ...)))