在另一列上排名一列

时间:2012-12-20 14:27:09

标签: mysql sql ranking

我有一张表格:

userid  rank  name
-------------------
1       4     raj
1       90    frank
1       100   neeta
1       123   liz
2       2     liz
2       20    neeta
2       23    frank
2       222   raj

我需要将其转换为

userid  min_rank  next_min_rank
-------------------------------
1       raj       frank
2       liz       neeta

我一直在网上搜索这个问题很长一段时间但找不到解决方案。

你能帮忙吗?

4 个答案:

答案 0 :(得分:2)

此查询将选择最小等级,以及每个用户的下一个等级:

select s.userid, s.min_rank, min(users.rank) as next_rank
from (
  select userid, min(rank) as min_rank
  from users
  group by userid) s left join users
  on users.userid = s.userid and s.min_rank<users.rank
group by s.userid

ant这将显示名称:

select t.userid, t1.name, t2.name
from (
  select s.userid, s.min_rank, min(users.rank) as next_rank
  from (
    select userid, min(rank) as min_rank
    from users
    group by userid) s left join users
    on users.userid = s.userid and s.min_rank<users.rank
  group by s.userid ) t
  left join users t1 on t.userid=t1.userid and t.min_rank=t1.rank
  left join users t2 on t.userid=t2.userid and t.next_rank=t2.rank

结果是:

1  raj  frank
2  liz  neeta

如果可能有多个具有相同排名的用户,则取决于您希望如何处理这种情况,您可以添加以下内容:

group by t.userid

只显示其中一个。也许您也可以在选择中使用GROUP_CONCAT(t1.name), GROUP_CONACT(t2.name)

答案 1 :(得分:2)

不是最优雅的一个。但试一试。

查询:

select b.userid, x.name1, b.name  as name2
from ranks b
join 
(
select a.userid, min(a.rank), a.name as name1
      from ranks a
      group by a.userid
) as x
on x.userid = b.userid
where (b.userid, b.rank, b.name) not in
(
select a.userid, min(a.rank), a.name
      from ranks a
      group by a.userid
)
group by b.userid
;

结果:

USERID  NAME1   NAME2
1       raj     frank
2       liz     neeta

答案 2 :(得分:1)

这确实对我有相同的数据

SELECT  N1.USERID AS USERID,N1.NAME AS MIN_RANK, N2.NAME AS NEXT_RANK 
FROM (SELECT USERID,NAME FROM TABLE1 WHERE RANK IN(SELECT  Min(Table1.rank) AS MinOfrank FROM Table1 GROUP BY Table1.UserID))  N1,
(SELECT USERID,NAME FROM TABLE1 WHERE RANK IN (SELECT Min(RANK) AS Expr1 FROM TABLE1 WHERE (TABLE1.rank) Not In (SELECT MIN(RANK) FROM TABLE1 GROUP BY USERID)  GROUP BY USERID))  N2 
WHERE
N1.USERID=N2.USERID;

希望它有所帮助!!

答案 3 :(得分:0)

试试这个:

select a.userid , a.name minRank, 
       (select name from usertable where userid =a.userid and rank>a.rank 
        order by rank limit 1) nextMinRank
From (Select userid, name ,rank from usertable order by rank) as a
Group by userid, rank