如何根据他们的积分选择前3名用户

时间:2018-03-28 06:38:05

标签: sql logic mysql-workbench limit

如何构建一个SQL,以满足下面的场景。

UserID | point
 001   |  100
 002   |  99
 003   |  98
 004   |  98
 005   |  97

选择前3名得分

UserID | point
 001   |  100
 002   |  99
 003   |  98
 004   |  98

但是,如果我按点desc命令并使用限制3功能,则只显示

UserID | point
 001   |  100
 002   |  99
 003   |  98

在这种情况下,004用户被排除在外。

2 个答案:

答案 0 :(得分:0)

SELECT t1.UserID, t1.point
FROM table1 t1
INNER JOIN
   (SELECT point FROM Table1 GROUP BY point ORDER BY point DESC LIMIT 3) as T2
On t1.point=t2.point

OR

SELECT Userid,
             point 
             FROM (SELECT    Userid,
             point,
             CASE WHEN 
                @point=t.point THEN
                  @curRank
                ELSE @curRank := @curRank + 1
               END AS rank,
             @point:=t.point AS varpoint
      FROM      Table1 t, (SELECT @curRank := 0, @point=null) r
      ORDER BY  point DESC) x
      WHERE rank<=3

现场演示

  

http://sqlfiddle.com/#!9/abf718/30

输出

Userid  point
1   100
2   99
3   98
4   98

答案 1 :(得分:0)

试试这个:

SELECT Y.UserID, Y.point
FROM YourTable Y
JOIN (
    SELECT Distinct point 
    FROM YourTable 
    ORDER BY point DESC 
    LIMIT 3) D ON D.Point = Y.Point