Can anyone help me answer why my query returns a syntax error? I'm working on the Hackerrank problem linked here.
Here's the code I wrote:
SELECT MAX(SELECT e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
WHERE e.salary * e.months = max_tot_earnings
I get the following syntax error:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT e1.salary * e1.months FROM Employee as e1) as max_tot_earnings, COUNT(e.e' at line 1
I know that the subquery doesn't have a syntax error. It runs just fine when run on its own. I was also able to work around the problem, so the purpose of this question is to try and figure out what's going on. I was able to solve the problem with the query shown below:
SELECT (SELECT e1.salary * e1.months as tot_earnings FROM Employee as e1 ORDER BY tot_earnings DESC LIMIT 1) as max_tot_earnings, COUNT(e.employee_id)
FROM Employee as e
GROUP BY e.salary, e.months
HAVING e.salary * e.months = max_tot_earnings
I found a few questions here that touch on using SELECT MAX(SELECT ...), but I didn't find answers for the two questions as phrased above. Questions one, two, and three.
In sum, I have two main questions:
- Why does the SELECT MAX(SELECT ...) approach return a syntax error? I've used MAX(SELECT ...) statements in HAVING before, so I'm puzzled. Are aggregate functions with subqueries just not allowed in SELECT?
- In my search online for an answer to #1, I have seen suggestions move the subquery in the FROM statement. Is this preferable to having the subquery in my SELECT statement (as in my eventual solution shown above)?