Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Combining sum and max aggregate function

Tags:

sql

mysql

How do I get the max value from the following query:

select sum(hours) from works_on group by pno;   
+------------+
| sum(hours) |
+------------+
|      52.50 |
|      50.00 |
|      55.00 |
|      25.00 |
|      55.00 |
+------------+

What I want is:

|      55.00 |
|      55.00 |

Thanks in advance.

like image 922
Tehreem Avatar asked Sep 11 '16 16:09

Tehreem


2 Answers

Use Having Clause and Sub-query. Something like this

SELECT Sum(hours) 
FROM   works_on 
GROUP  BY pno 
HAVING Sum(hours) = (SELECT Sum(hours) h 
                     FROM   works_on 
                     GROUP  BY pno 
                     ORDER  BY h DESC 
                     LIMIT  1) 

But it is really easy in SQL SERVER where we have TOP 1 with Ties which avoids the sub-query

like image 138
Pரதீப் Avatar answered Sep 26 '22 13:09

Pரதீப்


If you just want the maximum value, then one row will do:

select sum(hours)
from works_on
group by pno
order by sum(hours) desc
limit 1;

I'm not certain why you would want two rows, but then Prdp's answer is the right one.

like image 20
Gordon Linoff Avatar answered Sep 24 '22 13:09

Gordon Linoff