I'm doing an assignment which I tried to complete in SQL Server, as that's the language I will be using at my new job. I completed my query like this:
SELECT
h.hacker_id, h.name, sum(scr) AS tot
FROM
hackers AS h
JOIN
(SELECT
s2.hacker_id, s2.challenge_id, max(s2.score) AS scr
FROM
submissions s2
GROUP BY
s2.hacker_id, s2.challenge_id
HAVING
scr > 0) AS CET ON h.hacker_id = CET.hacker_id
GROUP BY
h.hacker_id
ORDER BY
tot DESC, h.hacker_id;
This query works (as in, it's a correct solution) in MySQL, but not in SQL Server. I figured I'd use a CTE instead of a SELECT
query in the JOIN
statement, so I adjusted this to use CTE instead like this:
WITH CTE AS
(
SELECT
s2.hacker_id, s2.challenge_id, max(s2.score) AS scr
FROM
submissions s2
GROUP BY
s2.hacker_id, s2.challenge_id
HAVING
scr > 0
)
SELECT
h.hacker_id, h.name, sum(scr) as tot
FROM
hackers AS h
JOIN
CTE ON h.hacker_id = CTE.hacker_id
GROUP BY
h.hacker_id
ORDER BY
tot DESC, h.hacker_id;
but this throws an error:
Invalid column name 'scr'.
(it says on Line 6 but from experience the website I use to complete these assignments can be a bit iffy with line indicators of errors).
Could someone please shed some light into what I have missed, and a working example for SQL Server?
(And of course, general criticism of the code itself is very much welcome, I want to become good at this).