I have a record of students and I need to group them by age. I have this scenario:
- If Age group has only one member, display his/her name and sex
- Else
- Display 'SOME STRING' as name
- Check sex of members, if All FEMALE, return FEMALE. If all MALE, return MALE, else return MIX
I came up with this query
SELECT Count(id) as GROUP_SIZE,
CASE WHEN COUNT(id) = 1 THEN name ELSE 'SOME STRING' END as name,
CASE WHEN COUNT(id) = 1 THEN sex ELSE (
CASE WHEN COUNT(CASE WHEN sex = 'MALE' THEN 1 END) = 0 THEN 'FEMALE'
WHEN COUNT(CASE WHEN sex = 'FEMALE' THEN 1 END) = 0 THEN 'MALE'
ELSE 'MIX'
END
) END as sex
FROM students GROUP BY age
This query output my desired scenario but I have multiple calls to Count(id). Will this impact performance as multiple Count was called? Or if Count(id) was performed once, will it have a constant time on succeeding calls to Count(id)? I tried CASE WHEN GROUP_SIZE
but it is not working. Please advise how I can improve this. Thanks.