Search code examples
mysqlgroup-bymysql-error-1111

Getting the "[Err] 1111 - Invalid use of group function" error


I'm currently doing this query:

SELECT Date_Format(M.Signupdate,"%Y-%m") as YearMonth,
SUM(IF(Count(H.Nr) >= 0,1,0)) ,
SUM(IF(Count(H.Nr) >= 1,1,0)) ,
SUM(IF(Count(H.Nr) >= 2,1,0)) ,
SUM(IF(Count(H.Nr) >= 3,1,0)) 
FROM people M 
INNER JOIN History H ON H.login = M.Login 
WHERE
M.Masteraccount = "" AND
M.logincount > 5 AND
DATEDIFF(M.lastlogin,M.Signupdate) >= 3 AND
DATEDIFF(H.EntryDate,M.Signupdate) <= 151
GROUP BY YearMonth ORDER BY YearMonth ;

However, I keep getting the "[Err] 1111 - Invalid use of group function" error. If I remove the SUM's it's working just fine. Does anyone have the answer for me please?


Solution

  • You cannot use the alias in the GROUP BY. You will need to place the Date_Format(M.Signupdate,"%Y-%m") in the GROUP BY to get this to work. Also you cannot nest aggregate functions so you will need to use a subquery to get the count, then use sum:

    select YearMonth,
        SUM(IF(CountNR >= 0,1,0)) ,
        SUM(IF(CountNR >= 1,1,0)) ,
        SUM(IF(CountNR >= 2,1,0)) ,
        SUM(IF(CountNR >= 3,1,0)) 
    from
    (
        SELECT Date_Format(M.Signupdate,"%Y-%m") as YearMonth,
            Count(H.Nr) CountNR 
        FROM people M 
        INNER JOIN History H 
          ON H.login = M.Login 
        WHERE M.Masteraccount = "" AND
          M.logincount > 5 AND
          DATEDIFF(M.lastlogin,M.Signupdate) >= 3 AND
          DATEDIFF(H.EntryDate,M.Signupdate) <= 151
        GROUP BY Date_Format(M.Signupdate,"%Y-%m") 
    ) src
    GROUP BY YearMonth
    ORDER BY YearMonth;