在MySQL中按组排名 [英] Ranking by Group in MySQL

查看:140
本文介绍了在MySQL中按组排名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个只有一列的表,如下所示:

I have a table with one column as follows:

name
-------
Michael
Michael
Michael
Michael
John
John
John
Alex
Alex

我需要给它们排名:

name    | rank
--------|------
Michael |1
Michael |2
Michael |3
Michael |4
John    |1
John    |2
John    |3
Alex    |1
Alex    |2

我该怎么做?

推荐答案

mysql中没有任何可以直接执行此操作的方法,但是您可以在以下方法中进行破解:

There's nothing in mysql that lets you do this directly, but you can hack it in:

SET @prev := null;

SET @cnt := 1;

SELECT name, IF(@prev <> name, @cnt := 1, @cnt := @cnt + 1) AS rank, @prev := name
FROM yourtable
ORDER BY name

使用相同的基本逻辑,可以在客户端应用程序中轻松完成这种事情.

This sort of thing is easier done in your client app, using the same basic logic.

这篇关于在MySQL中按组排名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆