dongyuan9109 2016-05-07 15:18
浏览 104
已采纳

通过SQL查询获得团队排名

I have this SQL query for getting the rank number of a team in my database based on their 'point'.

SELECT id, points, team_name, FIND_IN_SET( points, (
    SELECT GROUP_CONCAT( points
    ORDER BY points DESC )
    FROM teams )
    ) AS rank
    FROM teams
    WHERE id = ?
    LIMIT 1

The problem I'm having is that given the scenario that two teams have the same points e.g. say there is 2 teams and each team has '0' points. The query returns rank '1' for both of the teams.

I want the team with the lower 'id' to have the higher rank between the teams with the same points.

For example say team1 and team2 both have '5' points. I want the team with the lower id to have rank 1.

How can I alter my query to do that?

Thanks

  • 写回答

1条回答 默认 最新

  • dsjuimtq920056 2016-05-07 15:21
    关注

    The method you are using has limited applicability in MySQL, because it depends on the length of the intermediate substring in the group_concat(). However, you can modify it for this purpose:

    SELECT id, points, team_name,
           FIND_IN_SET(CONCAT(points, ':', id),
                       (SELECT GROUP_CONCAT(points, ':', id ORDER BY points DESC, id )
                        FROM teams
                       )
                      ) AS rank
    FROM teams
    WHERE id = ?
    LIMIT 1;
    

    A better method is:

    select id, points, team_name,
           (select count(*)
            from teams t2
            where t2.points > t.points or
                  (t2.points = t.points and t2.id <= t.id)
           ) as rank
    from teams t
    where id = ?;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式