Search code examples
mysqlsqlaggregate-functionsmysql-error-1111

MySql Sql MAX and SUM error


select sum(value) as 'Value',max(value)
from table_name where sum(value)=max(sum(value)) group by id_name;

The error is: Invalid use of group function (ErrorNr. 1111)

Any idea?

Thanks.


Solution

  • Can you maybe try

    SELECT Value, MXValue
    FROM (
           select sum(value) as 'Value',max(value)  MXValue
           from table_name 
           group by id_name
         ) as t1
    order by value desc
    LIMIT 0,1
    

    From MySQL Forums :: General :: selecting MAX(SUM())

    Or you could try something like

    SELECT  id_name,
            Value
    FROM    (
                select id_name,sum(value) as 'Value'
                from table_name
                group by id_name
            ) t
    WHERE   Value = (
                        SELECT TOP 1 SUM(Value) Mx 
                        FROM table_name
                        GROUP BY id_name 
                        ORDER BY SUM(Value) DESC
                    )
    

    Or even with an Inner join

    SELECT  id_name,
            Value
    FROM    (
                select id_name,sum(value) as Value
                from table_name
                group by id_name
            ) t INNER JOIN
            (
                SELECT TOP 1 SUM(Value) Mx 
                FROM table_name
                GROUP BY id_name 
                ORDER BY SUM(Value) DESC
            ) m ON Value = Mx