how to rank over partition in MySql

女生的网名这么多〃 提交于 2019-12-11 09:09:43

问题


Im new use MySql database, I face the problem that I can solve it if in SQL server Database, but I cant do it in mysql this bellow my case

MyTable:

Name    Price
abs     100
abs     200
abs     60
trx     19
trx     20
abs     10
qwe     25
qwe     50
qwe     10
qwe     10

Result Expected:

Name    Price   Rank
abs      200    4
abs      100    3
abs      60     2
abs      10     1
qwe      50     4
qwe      25     3
qwe      10     2
qwe      10     1
trx      20     2
trx      19     1

could anyone help me how to make query like index result pict with Mysql


回答1:


Using variable you can find Rank. Like this:

SELECT Name, Price, Rank
FROM (
      SELECT Name,
             Price,
             CASE WHEN @name = Name
                     THEN @id:=@id+1
                  ELSE @id:=1
             END AS Rank,
             @name:= Name AS dummy
      FROM myTable, (SELECT @name:=NULL, @id:=0) AS t
      ORDER BY Name,Price
     ) AS x
ORDER BY Name, Price DESC, Rank DESC 

OUTPUT:

Name    Price   Rank
---------------------
abs      200    4
abs      100    3
abs      60     2
abs      10     1
qwe      50     4
qwe      25     3
qwe      10     2
qwe      10     1
trx      20     2
trx      19     1

Link to the Demo:

http://sqlfiddle.com/#!9/a98575/4



来源:https://stackoverflow.com/questions/50040359/how-to-rank-over-partition-in-mysql

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