选择具有重复值的行分组

时间:2012-08-29 15:20:33

标签: sql oracle10g

我有两个看起来像这样的表

表狗:

PK, color
1,  red
2,  yellow
3,  red
4,  red
5,  yellow

狗有玩具。

桌上玩具

PK, FK, name
1,  2,  bowser
2,  2,  oscar
3,  3,  greg
4,  4,  alp
5,  4,  hanson
6,  5,  omar
7,  5,  herm

我需要一个查询来选择拥有多个玩具的所有黄狗的数量。

我在想某些事情:

Select count(*)
from toys t, dogs d
where t.fk = d.pk
and d.color = 'yellow'
group by t.fk    
having count(t.fk) > 1;

它应该返回2.但它会带回多行

1 个答案:

答案 0 :(得分:1)

select count(*)
from (
    select FK
    from Toys t
    inner join Dogs d on t.FK = d.PK
    where d."color" = 'yellow'
    group by FK
    having count(*) > 1
)

SQL Fiddle Example

相关问题