I tried something like this in the query but it returns an error
AVG(IF(sex = 'm', max(score),0)) as avg-m
You can't use one aggregate function within another (in this case, MAX()
within AVG()
)—what would that even mean? Once one has discovered the MAX()
of the group, over what is there to take an average?
Instead, you want to take the AVG()
of score
values where the sex matches your requirement; since AVG()
ignores NULL
values and the default for unmatched CASE
expressions is NULL
, one can simply do:
SELECT parentID,
COUNT(*) offspring,
SUM(sex='m') m,
SUM(sex='f') f,
AVG(CASE sex WHEN 'm' THEN score END) `avg-m`,
AVG(CASE sex WHEN 'f' THEN score END) `avg-f`,
AVG(score) `avg-both`
FROM sexb_1
GROUP BY parentID
HAVING `avg-both` > 11
See it on sqlfiddle.