Ranking by Group in MySQL

后端 未结 2 381
悲哀的现实
悲哀的现实 2020-12-17 07:34

I have a table with one column as follows:

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

I need to rank them to giv

相关标签:
2条回答
  • 2020-12-17 07:56

    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;
    
    0 讨论(0)
  • 2020-12-17 08:02

    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.

    0 讨论(0)
提交回复
热议问题