0

我有一张这样的桌子

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
4

3 回答 3

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'
于 2012-07-21T10:29:59.767 回答
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
于 2012-07-21T10:33:10.953 回答
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
于 2012-07-21T12:46:27.833 回答