SELECT Score, (SELECT COUNT(*) FROM (SELECT DISTINCT Score FROM Scores WHERE Score >= s.Score) AS tmp) AS Rank
FROM Scores s
ORDER BY Score DESC
谁能告诉我为什么最里面的子查询不知道 s.score 列?
SELECT Score, (SELECT COUNT(*) FROM (SELECT DISTINCT Score FROM Scores WHERE Score >= s.Score) AS tmp) AS Rank
FROM Scores s
ORDER BY Score DESC
谁能告诉我为什么最里面的子查询不知道 s.score 列?
那correlated subquery
("tmp") 嵌套太深,实际上外部查询不知道“tmp”的细节:
SELECT
Score
, (
SELECT
COUNT(*)
FROM ( ------------------------------
SELECT DISTINCT
Score
FROM Scores
WHERE Score >= s.Score
) AS tmp ----------------------------
)
AS rank
FROM Scores s
ORDER BY
Score DESC
;
您可以简单地使用count(distinct score)
并删除不必要的层。但是还要注意,必须非常准确地确定哪些列用于什么目的,因此如果没有定义别名,请确保在每个列引用前加上表别名或表名。没有例外。
SELECT
s.Score
, (
SELECT
COUNT(DISTINCT s2.Score)
FROM Scores s2
WHERE s2.Score >= s.Score
)
AS rank
FROM Scores s
ORDER BY
s.Score DESC
;
ps:rank()
是一个函数名,所以我不太热衷于使用“rank”作为列名,因为它会让人感到困惑。
用于 MS SQL Server(对不起,误读了标签,但留给其他读者)
我鼓励避免在 select 子句中使用相关的子查询,这样做更有效,并且 MS SQL Server 中from clause
的apply operator
可用功能非常适合:
SELECT
s.Score
, ca.[rank]
FROM Scores s
CROSS APPLY (
SELECT
COUNT(DISTINCT s2.Score) AS [rank]
FROM Scores s2
WHERE s2.Score >= s.Score
) ca
ORDER BY
s.Score DESC
;