我有提到的类似问题in this thead
但它在 SQL Server 中,而 Mysql 不支持“分区依据”,因为我现在知道我能做什么?这是问题:
我有一个包含一些列的表:用户、类别、值
我想要进行一个查询,该查询将按值对所有用户进行排名,但会针对类别进行重置。
示例:
user1 CategoryA 10
user2 CategoryA 11
user3 CategoryA 9
user4 CategoryB 3
user1 CategoryB 11
查询将返回:
Rank User Category
1 user2 CategoryA
2 user1 CategoryA
3 user3 CategoryA
1 user1 CategoryB
2 user4 CategoryB
有什么想法吗?
最佳答案
编辑2:基于OP的评论:
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)
建议进行以下更改:
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;
演示 @ MySQL 5.5.32 Fiddle
关于Mysql 查询排名 (RowNumber) 和分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23344738/