SQL查询 - 结果不同

时间:2011-06-01 09:04:01

标签: sql join correlated-subquery

我有以下两个表:

People [*ID*, Name] 
Pet [*PetID*, OwnerID, Species, Name]

(OwnerID是ID的外键)

我希望数据库列出每个人以及他们拥有的不同种类的数量。例如,如果Bob(ID 1473)拥有狗,猫和另一只狗,则输出应为:

ID    | No. of Species
----------------------
1473  | 2

我意识到这需要相关的子查询或外连接,但我不确定如何做到这一点。任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

您可以使用count(distinct ...)

select  People.ID
,       count(distinct Species)
from    People
join    Pet
on      Pet.OwnerID = People.ID
group by
        People.ID

答案 1 :(得分:1)

试试这个

Select ID,[No. of Species] from People 
inner join 
  ( select Count(Species) as [No. of Species],OwnerID from Pet  
   group by OwnerID) d 
on Id = d.OwnerID

答案 2 :(得分:1)

select people.name, count(distinct pet.species)
from people, pet
where people.id = pet.ownerid
group by people.name