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
Can anyone tell me why s.score column unknown to the innermost subquery?
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
Can anyone tell me why s.score column unknown to the innermost subquery?
Copyright © 2021 Jogjafile Inc.
That
correlated subquery
("tmp") is too deeply nested, in effect the details of "tmp" are not known to the outer query:You could simply use
count(distinct score)
and just remove the unnecessary layer. However also note that it is imperative to be very precise about which columns are being used for what purpose, so make sure you preface EVERY column reference with a table alias or table name if no alias has been defined. No exceptions.ps:
rank()
is a function name, so I'm not really keen on using "rank" as a column name as it can get confusing.----
for MS SQL Server (sorry, misread the tags, but leaving it for other readers)
I would encourage avoid using correlated subqueries in the select clause, it is more efficient to do this within the
from clause
and theapply operator
available in MS SQL Server is ideal for this: