这是我的桌子:
+--------+-------+--------+--------+
| player | points| score1 | score2 |
+--------+-------+--------+--------+
| 1 | 12 | 9 | 1 |
| 2 | 12 | 14 | 2 |
| 3 | 10 | 12 | 3 |
| 4 | 9 | 10 | 4 |
| 5 | 8 | 10 | 4 |
+--------+-------+--------+--------+
要获得第二高的值,我使用了以下查询:
SELECT player,points FROM players
WHERE points= (SELECT DISTINCT(points) FROM players as p1
WHERE (SELECT COUNT(DISTINCT(points))=2 FROM players as p2
WHERE p1.points<= p2.points)) ORDER BY player
效果很好。但是现在我想得到的是两个条件:
条件1 :分DESC
条件2 :(score1-score2)DESC
此查询可以很好地使玩家获得第二高的值(检查点和得分1):
SELECT player,points FROM players
WHERE points= (SELECT DISTINCT(points) FROM players as p1
WHERE (SELECT COUNT(DISTINCT(points))=2 FROM players as p2
WHERE p1.points<= p2.points))
AND
WHERE score1= (SELECT DISTINCT(score1) FROM players as p1
WHERE (SELECT COUNT(DISTINCT(score1))=2 FROM players as p2
WHERE p1.score1<= p2.score1))
ORDER BY player
如何使用两个条件(点DESC AND(score1-score2)DESC)获得第二高的玩家?
答案 0 :(得分:2)
此查询将执行您想要的操作。它JOIN
自己players
,在第二张表中寻找所有排名高于第一张表中的玩家的玩家。在这种情况下,排名首先基于points
,然后在score1
和score2
之间的差异相等的情况下进行排名。排名第二的玩家是排名更高的玩家之一:
SELECT p1.*
FROM players p1
JOIN players p2 ON p2.points > p1.points
OR p2.points = p1.points AND (p2.score1 - p2.score2) > (p1.score1 - p1.score2)
GROUP BY p1.player
HAVING COUNT(p2.player) = 1
输出:
player points score1 score2
1 12 9 1
您还可以以类似的方式编写原始查询,使用p2.player < p1.player
作为条件,用相等的分数分隔玩家(模拟ORDER BY player
的效果):
SELECT p1.*
FROM players p1
JOIN players p2 ON p2.points > p1.points
OR p2.points = p1.points AND p2.player < p1.player
GROUP BY p1.player
HAVING COUNT(p2.player) = 1
输出:
player points score1 score2
2 12 14 2