7

我有一张表格:

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

4 回答 4

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
于 2012-12-20T15:06:05.467 回答
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)在选择上使用。

于 2012-12-20T14:38:49.580 回答
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;

希望能帮助到你!!

于 2012-12-20T16:26:39.947 回答
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
于 2012-12-20T14:38:44.523 回答