简体   繁体   中英

SQL query help needed joining within a table

I have a table called babynames that looks abit like this:

firstname |sex |year |count 
Bob |M| 2010| 150
Bob |M| 2009| 100
Bob |M| 2008| 122
Bob |F| 2007| 2
Bob |F| 2001| 1

What I want to do is get a list of all the baby names that are both female and male, so my query needs to pull all the firstname records that have at least two records in the table and are at least one M and one F.

It's getting late and my mind isn't working well tonight. Can anyone suggest a string that might help me achieve this task?

There are several ways to handle this. One would be to to use a COUNT(DISTINCT sex) = 2 in the HAVING clause. Be sure to GROUP BY firstname .

SELECT 
  firstname
FROM babynames
GROUP BY firstname
HAVING COUNT(DISTINCT sex) = 2

Here's a demo: http://sqlfiddle.com/#!2/5d221/1

Another would an INNER JOIN against 2 aliases of the same table, where one looks for M while the other looks for F . If a name isn't matched by both conditions, the join can't be made and it will get excluded from the output.

SELECT
  DISTINCT
  m.firstname
FROM
  babynames f
  INNER JOIN babynames m ON f.firstname = m.firstname
WHERE
  f.sex = 'F'
  AND m.sex = 'M'

http://sqlfiddle.com/#!2/5d221/3

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