我在下面有一个查询,它使用基于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
积分相反,但排名保持不变。
答案 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;
如果您需要添加条件:
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;