I have a table as below:
id | english | hindi | maths | science |
---|---|---|---|---|
1 | 80 | 76 | 90 | 79 |
2 | 8 | 63 | 80 | 69 |
3 | 50 | 50 | 80 | 69 |
4 | 80 | 80 | 80 | 69 |
5 | 80 | 50 | 70 | 69 |
I wrote a query to get total of all the marks for each student
SELECT SUM(english+hindi+maths+science) AS total FROM MARKS GROUP BY id);
Got the following result as expected
total |
---|
325 |
220 |
249 |
309 |
265 |
Now I am trying to query the maximum marks from total. I have tried the below code:
SELECT MAX(total)
from (SELECT SUM(english+hindi+maths+science) AS total
FROM MARKS
GROUP BY id);
But the code returns error, can anyone please explain why this doesn’t work in mySQL?
the error is
ERROR 1064 (42000): 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 ” at line 1
2
Answers
Your
group by
and sum makes no sense. You use sum to sum the values in a column, not a row. Here’s a solution usingrank()
that also provides you the id of themax(total)
. If you just want themax(total)
you can use the second solution.Fiddle
You’re getting that error because you’re missing the alias in your subquery, as already mentioned in the comments. Adding the alias will fix it:
One more option to solve this task is to use the
LIMIT
clause in combination with theORDER BY
clause to determine the biggest summed up value.Check the demo here.