在表中的所有用户中获得用户的等级

时间:2012-07-21 10:00:19

标签: sql database rank

我有一张这样的表

userEmail | views

  A          8
  B          3
  C          4
  A          2
  B          5

我希望获得特定用户的排名说B ..

我正在做的是:

SET @rank=0;
select @rank:=@rank+1 AS rank , userEmail,sum(views) as views from mtable where userEmail != 'null' Group By userEmail Order By views DESC 

这将输出如下内容:

rank  | userEmail | views

  1        A          10
  2        B           8
  3        C           4

我可以获得所有用户的排名,但如果我想看到只有一个用户的排名呢?

如果我将where userEmail = 'B'放在上面的查询

我会得到这个:

rank  | userEmail | views

  1        B           8

但它应该是这样的:

 rank  | userEmail | views

  2          B           8

3 个答案:

答案 0 :(得分:1)

正如Gordan指出我的第一个答案不是很标准。这是做同样事情的标准方法。

SELECT T.userEmail, T.views, RANK() OVER (ORDER BY T.views DESC) AS viewRank
FROM (
  select userEmail,sum(views) as views 
  from mtable 
  where userEmail != 'null' 
  Group By userEmail) AS T
Order By T.views DESC

在sql server 2005+和Oracle(使用OVER子句)中有一种特殊的方法可以做到这一点,但是一般的答案(必须与mysql一起使用)是使用where子句。像这样:

SET @rank=0;

SELECT T.rank, T.userEmail, T.views 
FROM (
  select @rank:=@rank+1 AS rank , userEmail,sum(views) as views 
  from mtable 
  where userEmail != 'null' 
  Group By userEmail Order By views DESC ) AS T
WHERE T.userEmail='somename@somewhere.com'

答案 1 :(得分:0)

在SQL中,下面的临时表检查用户可以查询相同的内容。

create table #tmp (randomno int,email varchar(10),viewsum int)
insert into #tmp select  ROW_NUMBER() over (order by sum(vi) desc) as 'rank', email,SUM(vi) 
from test
 group by email




select * from #tmp where email = 'B'
 drop table #tmp

答案 2 :(得分:0)

我正在回答这个问题,因为@Hogan声称要采用一般方法。有一种适用于所有SQL数据库的通用方法,而不是它。

一般方法需要自我加入:

select t.useremail, t.views, count(*) as rownumber
from t left join
     t tless
     on t.useremail = tless.useremail and
        t.views >= tless.views
group by t.useremail, t.views

如果您在视图上有重复项,则以下内容相当于密集排名:

select t.useremail, t.views, count(distinct tless.views) as denserank
from t left join
     t tless
     on t.useremail = tless.useremail and
        t.views >= tless.views
group by t.useremail, t.views

并且,由于查询没有明确提及数据库,因此在大多数数据库中,您只需使用:

select t.usermail, t.views, row_number() over (partition by usermail order by views)
from t