问题
i have the similar problem mentioned in this thead
but it's in SQL server and Mysql doesn't support "Partition By" as i know now what can i do? Here is the Question:
I have a table that has some columns: User, Category, Value
And I want to make a query that will give me a ranking, of all the users by the value, but reset for the category.
Example:
user1 CategoryA 10
user2 CategoryA 11
user3 CategoryA 9
user4 CategoryB 3
user1 CategoryB 11
the query would return:
Rank User Category
1 user2 CategoryA
2 user1 CategoryA
3 user3 CategoryA
1 user1 CategoryB
2 user4 CategoryB
Any ideas?
回答1:
Edit 2: Based on OP's comment:
it worked with just a little bit wrong ranking and that's in the first
rank
.when similarcategories
with samevalue
has the toprank
one of them is the first in therank
and other is 2nd but they must have the firstrank
(1)
Following change is suggested:
select rank, user, category, value
from (
select user, @cc:=category category, @cv:=value value
, case when @pc=@cc and @pv=@cv then @rn:=@rn
when @pc=@cc and @pv!=@cv then @rn:=(@rn+1)
else @rn:=1
end as rank
, @pc:=@cc as temp_currCat
, @pv:=@cv as temp_currVal
from user_category_values,
(select @pc:='', @cc:='',
@pv:='', @cv:='',
@rn:=0) row_nums
order by category asc, value desc
) results;
Demo @ MySQL 5.5.32 Fiddle
回答2:
You can use variables for this:
select rank, user, category
from (select t.*,
@rank := if(@cat = category, @rank + 1, 1) as rank,
@cat := category
from table t cross join
(select @cat := '', @rank := 0) const
) t
order by category, rank;
来源:https://stackoverflow.com/questions/23344738/mysql-query-for-rank-rownumber-and-groupings