crm crm - 3 months ago 14
MySQL Question

MySQL Invalid use of group function with max()

I am trying to select a boolean value where order.lastUpdated is older than 30 minutes ago, but I get the error:


SQL state [HY000]; error code [1111]; Invalid use of group function;
nested exception is java.sql.SQLException: Invalid use of group
function


Here is the query:

select
c.externalReference channelReference,
c.id channelId,
max(o.lastUpdated) lastUpdated,
sum(if(max(o.lastUpdated) < date_sub(now(), interval 30 minute), 0, 1)) beforeThreshold
from channel c
join order_item o on c.id = o.channelId
where date(o.lastUpdated) = date(now())
and o.lastUpdated > date_sub(now(), interval 1 hour)
group by c.externalReference;


How can I return a boolean value if
o.lastUpdated
is older than 30 minutes ago where I have to use
max()
?

Answer

You can't nest aggregation functions like SUM() and MAX(). You need to do the inner one in a subquery.

SELECT c.externalReference AS channelReference,
       c.id AS ChannelId
       o.lastUpdated,
       SUM(IF(o.lastUpdated < DATE_SUB(NOW(), INTERVAL 30 MINUTE), 0, 1) AS beforeThreshold
FROM channel AS c
JOIN (SELECT channelId, MAX(lastUpdated) AS lastUpdated
      FROM order_item
      WHERE DATE(lastUpdated) = TODAY()
        AND lastUpdated > DATE_SUB(NOW(), INTERVAL 1 HOUR)
      GROUP BY channelId) AS o
ON c.id = o.channelId
GROUP BY c.externalReference
Comments