0

我在下面有一个查询,它使用基于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

分数是相反的,但排名保持不变。

4

1 回答 1

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;

小提琴

如果需要添加条件:

 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;

小提琴

于 2013-07-08T17:26:43.247 回答