Mysql Query for Rank (RowNumber) and Groupings

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-13 08:02:02

问题


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 similar categories with same value has the top rank one of them is the first in the rank and other is 2nd but they must have the first rank (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

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