0

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

4

2 回答 2

0

试试这个查询 -

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
于 2012-08-06T10:03:17.080 回答
0

这就是你要找的:

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

您无法直接获得三列结果,因为只有一列包含性别。

于 2012-08-06T09:59:53.820 回答