I have a Database named Students, with the attribute 'Grade' to store the grades of students. I wrote 2 following spinnets of code and expected that I would have the same result:
1.
SELECT * FROM (SELECT * FROM dbo.Students) AS A
WHERE A.Grade = (SELECT MAX(Grade) FROM A)
WITH A AS (SELECT * FROM Students)
SELECT * FROM A
WHERE A.Grade = (SELECT MAX(Grade) FROM A)
But actually, when I executed the first code, I got an error like "Invalid object name 'A'." I cannot understand why I got that error because I think the logic of the two codes is the same. Can anyone explain this to me, please!!
Thank you very much!!
CodePudding user response:
You name a subquery here:
...(SELECT * FROM dbo.Students) AS A -- here
, but use this alias (A) inside same query here:
...(SELECT MAX(Grade) FROM A) -- here
It's not allowed.
When you use a CTE (WITH A AS...), you claim A at first and then use it properly.