如何根据mysql中的排名对数据进行分组

时间:2016-09-19 13:45:40

标签: mysql database

我正在努力创建查询我希望根据分数按客户ID分组数据。客户有多个分数我想根据他们的排名结合客户分数 在表结构下面

CREATE TABLE `score` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` varchar(10) DEFAULT NULL,
  `score` int(6) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=latin1;


insert  into `score`(`id`,`customer_id`,`score`) 
values (1,'C1',20),   (2,'C1',10),(3,'C3',30),(4,'C1',30),(5,'C2',40),
 (6,'C2',50),(7,'C2',20),(8,'C1',50),(9,'C3',20),
(10,'C1',50);

 Table result look like 
   id    customer_id    score
    1       C1                 20               
    2       C1                 10
    3       C3                 30
    4       C1                 30              
    5       C2                 40
    6       C2                 50
    7       C2                 20

欲望结果:

       customer_id          score    Rank
         C1                 30        1       
         C1                 20        2
         C1                 10        3
         C2                 50        1       
         C2                 40        2
         C2                 20        3
         C3                 30        1

2 个答案:

答案 0 :(得分:1)

您可以使用变量:

SELECT id, customer_id, score,
       @rnk := IF(@cid = customer_id, @rnk + 1,
                  IF(@cid := customer_id, 1, 1)) AS rank
FROM score
CROSS JOIN (SELECT @rnk := 0, @cid := '') AS v
ORDER BY customer_id, score DESC

Demo here

答案 1 :(得分:1)

试试这个

 SELECT
        a.score AS score,
        @rn := IF(@PREV = customer_id, @rn + 1, 1) AS rank,
        @PREV := customer_id AS cutomerId
    FROM score AS a
    JOIN (SELECT @PREV := NULL, @rn := 0) AS vars
    ORDER BY customer_id, score DESC, id