Mysql根据DESC级别和经验DESC计算排名

时间:2014-08-04 11:36:34

标签: mysql sql

基本上我有一个名为hiscores的表,我想搜索一个用户的昵称并获得他当前的排名,因为排名不存在,因为排名由lvl DESC组织,然后是Experience,所以我想要一个SQL查询,我搜索其名称 “player1”并且它使我排名第2或输入healdeal并获得排名1

 Table =  hiscores

id - nickname- lvl - experience

1   - healdeal - 99    - 1000

2   - philip   - 98    - 595

3   - Player1  - 98    - 620

4   - Mindblow - 52    - 35

我试过以下

SELECT (COUNT(*) + 1) AS rank FROM hiscores WHERE lvl >(SELECT lvl FROM hiscores WHERE nickname="player1")

3 个答案:

答案 0 :(得分:1)

假设这是MySQL,这将起作用:

select @rownum:=@rownum+1 Rank, 
h.* 
from hiscores h, 
(SELECT @rownum:=0) r 
order by level desc, experience desc

SQLFiddle

如果这是MS SQL Server 2005以后,您可以直接使用窗口函数,如下所示:

select *, rank() over (order by level desc, experience desc) Rank
from hiscores

在任何一种情况下,如果你想按昵称过滤,你可以将上面的表达式放入子查询中并按昵称过滤,即

select * from
(<ranking expression from above>) rankedresults
where nickname = <input>

答案 1 :(得分:0)

我明白了。你正试图计算排名。我想这可能会这样做:

select count(*) as rank
from hiscores hs cross join
     (select hs.*
      from hiscores
      where nickname = 'player1'
     ) hs1
where hs.lvl > hs1.lvl or
      hs.lvl = hs1.lvl and hs.experience >= hs1.experience;

实际上,如果您在experiencelvl都有联系,那么这可能是更好的排名:

select 1 + count(*) as rank
from hiscores hs cross join
     (select hs.*
      from hiscores
      where nickname = 'player1'
     ) hs1
where hs.lvl > hs1.lvl or
      hs.lvl = hs1.lvl and hs.experience > hs1.experience;

答案 2 :(得分:0)

如果您使用的是MSSQL 2005+。你可以这样做:

测试数据:

DECLARE @tbl TABLE(id INT,nickname VARCHAR(100),lvl INT, experience INT)

INSERT INTO @tbl
VALUES
(1 ,'healdeal',99,1000),
(2 ,'philip',98,595),
(3 ,'Player1',98,620),
(4 ,'Mindblow',52,35)

<强>查询

;WITH CTE
AS
(
    SELECT
        RANK() OVER(ORDER BY lvl DESC,experience DESC) AS rank,
        tbl.*
    FROM
        @tbl AS tbl
)
SELECT
    *
FROM
    CTE
WHERE
    CTE.nickname='Player1'

<强>输出

2   3   Player1 98  620