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列不知道最里面的子查询?
答案 0 :(得分:0)
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子句中使用相关子查询,在from clause
中执行此操作更有效,并且MS SQL Server中可用的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
;