我有一个包含一些列的表:User,Category,Value
我想创建一个查询,根据值给出一个所有用户的排名,但重置该类别。
示例:
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
有什么想法吗?
我编写查询并指定类别,它可以工作但是我必须编写循环并且它非常慢。
答案 0 :(得分:44)
在排名函数OVER clause
中使用“分区依据”SELECT
Rank() over (Partition by Category Order by Value, User, Category) as ranks,
Category, User
FROM
Table1
Group By
User, Category, Value
Order by
ranks asc
答案 1 :(得分:3)
Select User, Category,
(Select Count(*) From Table
Where Category = A.Category
And Value <= A.Value) Rank
From Table A
Order By Category, Value
如果Value可以有重复项,那么你必须决定是否要“计算”欺骗(等于RANK)(不等于DENSE_RANK,而不是x @shannon)
普通等级:
Select User, Category,
(Select 1 + Count(*) From Table -- "1 +" gives 1-based rank,
Where Category = A.Category -- take it out to get 0-based rank
And Value < A.Value) Rank
From Table A
Order By Category, Value
“密集”等级:
Select User, Category,
(Select 1 + Count(Distinct Value) -- "1 +" gives 1-based rank,
From Table -- take it out to get 0-based rank
Where Category = A.Category
And Value < A.Value) Rank
From Table A
Order By Category, Value