No, the problem comes before you write the INSERT
. Try running just the plain SELECT
and you'll see exactly the same error. Logically, WHERE
runs before SELECT
so you can't refer to aliases introduced by the latter in the former.
This should work:
INSERT INTO #tempKleerkast(IDKleerkastPersoon,ID_Persoon,rk)
SELECT IDKleerkastPersoon, ID_Persoon, rk
FROM (
SELECT
IDKleerkastPersoon, kk.ID_Persoon,
ROW_NUMBER() OVER (PARTITION BY kk.ID_Persoon
ORDER BY kk.IDKleerkastPersoon DESC) AS rk
FROM KleerkastPerPersoon kk
WHERE kk.ID_Persoon IS NOT NULL) t
WHERE rk = 1
(I also removed the DISTINCT
since one of the columns listed was also a column listed in the PARTITION BY
clause and we're only selecting one row from each partition)