简体   繁体   中英

SQL JOIN PARENT AND CHILD and GET count of PARENT and CHILD RECORDS

I have this Query which is giving me hard time to figure out what the issue, your advice is appreciated.

 SELECT
  cooperatives.island, cooperatives.id,
  COUNT(
    CASE WHEN members.gender = 'Male' THEN 1 ELSE NULL END
  ) AS males,
  COUNT(
    CASE WHEN members.gender = 'Female' THEN 1 ELSE NULL END
  ) AS females,
  COUNT(members.gender) AS genderall
FROM
  cooperatives
JOIN members ON cooperatives.id= members.c_id
WHERE
  1 = 1 
GROUP BY
  cooperatives.island

What am trying to do is to get result like this

SQL result

Which is working BUT what I need to add there is another column which will show a number of cooperatives from each Island.

I suspect you want:

SELECT c.island, COUNT(DISTINCT c.id) as num_cooperatives,
       SUM(m.gender = 'Male') AS males,
       SUM(m.gender = 'Female') AS females,
       COUNT(m.gender) AS genderall
FROM cooperatives c JOIN
     members m
     ON c.id = m.c_id
GROUP BY c.island;

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