在MySQL中按组排名

use*_*867 2 mysql rank

我有一个包含一列的表格如下:

name
-------
Michael
Michael
Michael
Michael
John
John
John
Alex
Alex
Run Code Online (Sandbox Code Playgroud)

我需要对它们进行排名以给出:

name    | rank
--------|------
Michael |1
Michael |2
Michael |3
Michael |4
John    |1
John    |2
John    |3
Alex    |1
Alex    |2
Run Code Online (Sandbox Code Playgroud)

我该怎么做?

Yat*_*edi 6

简单的,

CREATE TABLE customer (
name CHAR(30) NOT NULL,
rank MEDIUMINT NOT NULL AUTO_INCREMENT,
PRIMARY KEY (name,rank)) ENGINE=MyISAM;

INSERT INTO customer (name) VALUES
('Michael'),('Michael'),('John'),('Alex'),('Michael'),('John');

SELECT * FROM customer ORDER BY name,rank;
Run Code Online (Sandbox Code Playgroud)

  • 它将按照他想要的方式工作,它将仅根据名称添加序列。试试吧。 (2认同)

Mar*_*c B 5

在mysql中没有任何东西可以让你直接执行此操作,但你可以在以下方面进行破解:

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
Run Code Online (Sandbox Code Playgroud)

使用相同的基本逻辑,在您的客户端应用程序中更容易完成此类操作.