Ranking by Group in MySQL

江枫思渺然 提交于 2019-11-29 05:17:58

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.

Simple,

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;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!