22

我有一个包含一些列的表:用户、类别、值

我想做一个查询,它会给我一个排名,所有用户的价值,但为类别重置。

例子:

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

有任何想法吗?

我编写查询并指定类别,它可以工作,但是我必须编写循环并且它非常慢。

4

2 回答 2

44

在排名函数OVER 子句中使用“Partition by”

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
于 2009-07-16T19:24:19.343 回答
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,thanx @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
于 2009-07-16T19:21:21.767 回答