我有以下表格:
person( sin, name, address)
owner(dogowner_id, dog_id, is_primary_owner_of_dog)
dog( dog_no, breed_id )
dog_breed( breed_id, breed )
您如何找到至少10个黄色实验室的主要(主要拥有者)的所有人?我对此非常困惑,帮助我非常感激。
编辑:请不要嵌套查询和聚合!
答案 0 :(得分:2)
一种方法是在IN
表上利用person
:
SELECT * FROM person
WHERE sin IN (
SELECT dogowner_id FROM owner o
JOIN dog d ON o.dog_id = d.dog_no
JOIN dog_breed b ON b.breed_id = d.breed_id
WHERE is_primary_owner_of_dog AND
b.breed = 'Yellow Lab'
GROUP BY dogowner_id
HAVING COUNT(dogowner_id) >= 10
)
内部查询将确定“主要所有者”拥有至少 10只狗的内容,然后外部查询将返回相应的person
条记录。
答案 1 :(得分:0)
select count(*), dogowner
from owner
inner join dog on dog.dog_no = owner.dog_id
inner join dob_breed on dog.breed_id = dog_breed.breed_id
where dog_breed.breed = 'Yellow Lab'
group by dogowner
having count(*) >=10
答案 2 :(得分:0)
您使用join
和group by
执行此操作:
select dogowner, count(*) as numyellowlabs
from owner o
dog d
on o.dog_id = d.dog_no join
dog_breed db
on d.breed_id = db.breed_id
where breed = 'Yellow Lab'
group by dogowner
having count(*) >=10;
答案 3 :(得分:0)
SELECT count(*) AS numberOfDogs, dogowner AS dogOwner
FROM owner AS o
INNER JOIN dog AS d
ON d.dog_no = o.dog_id
INNER JOIN dob_breed as b
ON d.breed_id = b.breed_id
WHERE b.breed = 'Yellow Lab'
AND o.is_primary_owner_of_dog = "True"
GROUP BY dogowner
HAVING count(*) >=10
其他查询非常接近......缺少的部分是“至少10个黄色实验室的主要(主要拥有者)?”我不知道is_primary_owner_of_dog的值是什么...是/否, 0/1,是/否....因此需要相应地修改查询。但除此之外,这应该可以解决问题。
答案 4 :(得分:-1)
考虑到不存在嵌套查询和聚合,您可以使用分析函数COUNT()和连接来完成任务,如下所示:
Select P.*
From Person P Inner Join (Select DISTINCT Dogowner_Id, Count(O.Dog_Id) Over (Partition By O.Dogowner_Id) Dog_Count
From Owner O Inner Join Dog D On O.Dog_Id = D.Dog_No
Inner Join Dog_Breed Db On D.Breed_Id = Db.Breed_Id
Where Db.Breed = 'Yellow Lab'
And O.Is_Primary_Owner_Of_Dog = 1) Counts
On Counts.Dogowner_Id = P.Sin
Where Counts.Dog_Count >= 10