2

I am trying to write a SQL statement that selects data out of a table where an individual has multiple values in the same column. For example, based on the table below: I need a query to select all of the rows for all of the individuals who have both a bat and a baseball in the “Toy” column.

------------------------
| ID | Name | Toy      |
------------------------
|  1 | Jack | Bat      |
|  2 | Jim  | Baseball |
|  3 | Jack | Baseball |
|  4 | John | Bat      |
|  5 | Jim  | Football |
|  6 | Jack | Glove    |
------------------------

I would like the results to be something like:

-------------------
| Name | Toy      |
-------------------
| Jack | Bat      |
| Jack | Baseball |
-------------------

I hope this makes sense. Thanks.

1
  • You're going to need to clarify this. I thought you wanted a query that selects ALL names that have more than one toy. Juergen, and others, apparently, think you want one where there is a specific combination of two toys. Commented Nov 12, 2013 at 17:48

1 Answer 1

5
select distinct t.name, t.toy
from your_table t
where name in 
(
  select name
  from your_table
  where toy in ('bat','baseball') 
  group by name
  having count(distinct toy) = 2
)
and toy in ('bat','baseball') 

If you just need the name you can do

  select name
  from your_table
  where toy in ('bat','baseball') 
  group by name
  having count(distinct toy) = 2

SQLFiddle demo

Sign up to request clarification or add additional context in comments.

1 Comment

No, I want =2 because it is exactly 2. Always, because of the where condition.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.