问题
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