Description:
Julia asked her students to create some coding challenges. Write a query to print the hacker_id, name, and the total number of challenges created by each student. Sort your results by the total number of challenges in descending order. If more than one student created the same number of challenges, then sort the result by hacker_id. If more than one student created the same number of challenges and the count is less than the maximum number of challenges created, then exclude those students from the result.
Here is my SQL code:
SELECT
H.HACKER_ID AS 'HACKER_ID', NAME,
COUNT(NAME) AS 'COUNT1'
FROM
HACKERS H
JOIN
CHALLENGES C ON H.HACKER_ID = C.HACKER_ID
GROUP BY
H.HACKER_ID, NAME
HAVING
COUNT1 = (SELECT MAX(S1.COUNT3)
FROM
(SELECT COUNT(HACKER_ID) AS 'COUNT3'
FROM CHALLENGES
GROUP BY HACKER_ID) AS S1)
OR COUNT1 IN (SELECT S2.COUNT2
FROM
(SELECT HACKER_ID, COUNT(HACKER_ID) AS 'COUNT2'
FROM CHALLENGES
GROUP BY HACKER_ID) AS S2
GROUP BY
S2.COUNT2
HAVING
COUNT(S2.COUNT2) = 1)
ORDER BY
COUNT1 DESC, H.HACKER_ID;
Question:
Actually this code can run in Mysql environment and got the correct result but can't run in SQL Server environment and I get an error
Invalid column name 'COUNT1'
I would like to ask what's the exact error here in SQL Server and what's the difference between the Mysql and SQL Server because this error happens only in SQL Server but not in Mysql