2014-04-28 92 views
0

我有類似的問題提到in this theadMySQL查詢的排名(ROWNUMBER)和分組

但它在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 

任何想法?

+0

不知道我是否能看到你想要做什麼,看看' GROUP BY' –

回答

0

可以使用變量此:

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; 
1

編輯2:基於OP的評論:

它只是一點點錯誤的排名工作,這是在第一rank 。當類似categoriesvalue相同時,頂部rank其中之一是rank中的第一個,其他是第二個但它們必須具有第一個rank(1)

如下更改建議:

select rank, user, category, value 
from (
    select user, @cc:=category category, @cv:=value value 
    , case when @[email protected] and @[email protected] then @rn:[email protected] 
      when @[email protected] and @[email protected] then @rn:=(@rn+1) 
      else @rn:=1 
     end as rank 
    , @pc:[email protected] as temp_currCat 
    , @pv:[email protected] 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

+0

Ravinder和Gordon Linoff thanx爲你的快速回復。我測試過Ravinder的它運行完美,但問題是,在同一類別中具有相同的值,它具有增加排名而不是相同ranknig。 Gordon Linoff我剛剛在小提琴中測試了你的代碼,它有錯誤 – vahidasadi

+0

@vahidasadi:檢查我更新的答案。 –

+0

對你來說非常好,對於help.it,這只是一點點錯誤的排名,並且在第一排位。當相似價值的類別具有最高排名時,他們之一排名第一,其他排名第二但他們必須具有第一等級(1) – vahidasadi