简体   繁体   中英

MySQL - Counting Groups That Meet Certain Criteria

I have the following tables:

Family

  • ID INT AUTO_INCREMENT
  • CountryOfResidence STRING

Person

  • ID INT AUTO_INCREMENT
  • FamilyID INT FOREIGN KEY
  • DOB DATE

I am trying to find the count of all the families by CountryOfResidence that contain somebody born before 1970.

I can't simply do a JOIN with Person and Family as that would give me the unique count of every person. I want the family to be counted only once when any person within the family is born before 1970.

Can someone help me craft this query? I feel like a subquery would accomplish what I am looking for, but I am afraid about the performance.

EDIT

Added SQL Fiddle: http://sqlfiddle.com/#!9/b92e3/1/0

Expected results:

------------------------------- 
|CountryOfResidence | count(*)|
|-----------------------------| 
|Poland             | 1       | 
|USA                | 1       |
-------------------------------

You can use EXISTS for this:

SELECT CountryOfResidence , COUNT(*)
FROM Family AS f
WHERE EXISTS (SELECT 1
              FROM Person AS p
              WHERE f.ID = p.FamilyID AND  Year(DOB) < 1970) 
GROUP BY CountryOfResidence 

Use COUNT(DISTINCT Family.ID) so you don't count all the duplicates due to the joins.

SELECT
  f.CountryOfResidence AS country,
  COUNT(DISTINCT f.ID) AS family_count_per_country
FROM Family AS f
INNER JOIN Person as p
  ON f.ID = p.FamilyID
WHERE p.DOB < '1970-01-01'
GROUP BY country

No reason you can't use a JOIN here. It does seem odd to me though to have a country of residence tied to a family and not a person.

SELECT
  f.CountryOfResidence AS country,
  COUNT(f.ID) AS family_count_per_country
FROM Family AS f
INNER JOIN Person as p
  ON f.ID = p.FamilyID
WHERE p.DOB < '1970-01-01'
GROUP BY country

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