简体   繁体   中英

MySQL - Do I need a nested query?

I need to write a query that displays, for each activity, a count of the number of males and number of females.

Preferably in a 3 column format, activity_name, male (computed column), female (computed column).

I think I may need to use nested queries, but I cannot figure out how. Or could this be done by just using GROUP BY?

My tables are:

Child child_id child_fname child_sname child_gender etc etc

Activity activity_id activity_name etc etc

Child_Activity_Item child_id activity_id

Thank you

this is what you are looking for:

SELECT  MaleList.Activity_Name,
        MaleList.totalMale,
        FemaleList.totalFemale,
FROM
(
    SELECT  a.Activity_ID, 
            a.Activity_Name,
            COUNT(c.child_gender) totalMale
    FROM    Activity a 
                INNER JOIN Child_Activity_Item b
                    on a.activity_id = b.activity_ID
                INNER JOIN Child c
                    on b.child_id =  c.child_id
    WHERE   c.child_gender = 'male'
    Group BY a.Activity_ID
) as MaleList INNER JOIN
(
    SELECT  a.Activity_ID, 
            a.Activity_Name,
            COUNT(c.child_gender) totalFemale
    FROM    Activity a 
                INNER JOIN Child_Activity_Item b
                    on a.activity_id = b.activity_ID
                INNER JOIN Child c
                    on b.child_id =  c.child_id
    WHERE   c.child_gender = 'female'
    Group BY a.Activity_ID
) as FemaleList 
    ON  MaleList.Activity_ID =  FemaleList.Activity_ID

you cannot directly get a three-column result because there is only only column that holds the gender.

Try this query -

SELECT
  a.activity_id,
  a.activity_name,
  COUNT(IF(c.child_gender = 'M', c.child_gender, NULL)) male,
  COUNT(IF(c.child_gender = 'F', c.child_gender, NULL)) female
FROM
  Activity a
  JOIN Child_Activity_Item ca
    ON ca.activity_id = a.activity_id
  JOIN Child c
    ON c.child_id = ca.child_id
GROUP BY a.activity_id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM