Mysql排名,asc或desc

时间:2013-07-08 16:56:46

标签: mysql ranking rank

我在下面有一个查询,它使用基于points的排名方法。问题是,如果我通过asc订购排名仍然显示1,2,3,4等而不是4,3,2,1。(或者如果只想获得一个人的排名(其中username = name1),结果来了返回1,而不是基于points的实际排名。我的代码如下:

SELECT username, @n := @n + 1 ranking, `1st places`, `2nd places`, `3rd places`, `avg`, `1st places` + `2nd places` + `3rd places` AS `points`
FROM (SELECT username,  
SUM(CASE WHEN rating = 1 THEN 10 ELSE 0 END) `1st places`,
SUM(CASE WHEN rating = 2 THEN 5 ELSE 0 END) `2nd places`,
SUM(CASE WHEN rating = 3 THEN 3 ELSE 0 END) `3rd places`,
format(avg(rating),0) `avg`

FROM contest_entries 
GROUP BY username 

) q, (SELECT @n := 0) n 
ORDER BY `points` desc  

所以我想要的是能够按points排名,但是如果我想通过asc排序,那么排名会反过来...... 4,3,2,1。这可能吗? ?

编辑*这是我使用上述代码时的样子。

username    ranking   1st places    2nd places  3rd places  avg points
name3          1       10               5            0       1    15
name1          2       10               0            0       1    10
name2          3       0                0            0       6     0

然而,当按点asc排序时,结果如下:

username    ranking   1st places    2nd places  3rd places  avg points
name2          1       0                0            0       6    0
name1          2       10               0            0       1    10
name3          3       10               5            0       1    15

积分相反,但排名保持不变。

1 个答案:

答案 0 :(得分:0)

select * from
(SELECT username, @n := @n - 1 ranking, `1st places`, `2nd places`, `3rd places`, `avg`, `1st places` + `2nd places` + `3rd places` AS `points`
FROM (SELECT username,  
SUM(CASE WHEN rating = 1 THEN 10 ELSE 0 END) `1st places`,
SUM(CASE WHEN rating = 2 THEN 5 ELSE 0 END) `2nd places`,
SUM(CASE WHEN rating = 3 THEN 3 ELSE 0 END) `3rd places`,
format(avg(rating),0) `avg`

FROM contest_entries 
GROUP BY username 

) q, (SELECT @n := count(distinct username)+1 from contest_entries) n 
ORDER BY `points` asc) resultset
order by ranking asc;

fiddle

如果您需要添加条件:

 select * from
(SELECT username, @n := @n - 1 ranking, `1st places`, `2nd places`, `3rd places`, `avg`, `1st places` + `2nd places` + `3rd places` AS `points`
FROM (SELECT username,  
SUM(CASE WHEN rating = 1 THEN 10 ELSE 0 END) `1st places`,
SUM(CASE WHEN rating = 2 THEN 5 ELSE 0 END) `2nd places`,
SUM(CASE WHEN rating = 3 THEN 3 ELSE 0 END) `3rd places`,
format(avg(rating),0) `avg`

FROM contest_entries 
GROUP BY username 

) q, (SELECT @n := count(distinct username)+1 from contest_entries)
 n 
ORDER BY `points` asc) resultset where username = 'name1'
order by ranking asc;

fiddle