我正在尝试编写一个SQL语句,用于从表中选择数据,其中一个人在同一列中有多个值。例如,基于下表:我需要一个查询来为“玩具”列中同时拥有蝙蝠和棒球的所有个人选择所有行。
------------------------
| ID | Name | Toy |
------------------------
| 1 | Jack | Bat |
| 2 | Jim | Baseball |
| 3 | Jack | Baseball |
| 4 | John | Bat |
| 5 | Jim | Football |
| 6 | Jack | Glove |
------------------------
我希望结果如下:
-------------------
| Name | Toy |
-------------------
| Jack | Bat |
| Jack | Baseball |
-------------------
我希望这是有道理的。感谢。
答案 0 :(得分:4)
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')
如果你只需要你可以做的名字
select name
from your_table
where toy in ('bat','baseball')
group by name
having count(distinct toy) = 2