Find the Supplier number for those suppliers who supply every part
I have the following tables:
Suppliers(Sno, Sname, Address)
Parts(Pno, Pname, Colour)
Catalogue(Sno, Pno, Price)
and I want to find the Sno of the suppliers who supply every part.
So far, I've written this:
SELECT s.sname
FROM suppliers s JOIN catalogue c
USING s.sno
Now how do I write the part "suppliers that supply every part"?
I was thin开发者_如何学Cking about having the count(*) from parts = count(pno) for each supplier Sno. Could someone please give me a hint/write the first part of the equality?
Thanks!
SELECT s.sname
FROM suppliers s
INNER JOIN catalogue c
ON s.Sno = c.Sno
GROUP BY s.sname
HAVING COUNT(c.Pno) = (SELECT COUNT(Pno) FROM Parts)
You're close. You need to add a group by/having clause with a subquery:
group by s.sname having count(*) = (select count(*) from catalogue)
Off the top of my head, you could write
SELECT s.Sno
FROM suppliers s
WHERE NOT EXISTS (
SELECT p.Pno
FROM parts p
WHERE NOT EXISTS (
SELECT c.*
FROM catalogue c
WHERE c.Pno = P.Pno
AND c.Sno = S.Sno
)
)
i.e. supplier where not exists (part that we don't supply), for a solution avoiding counts. No idea if this would be more or less efficient than the counts.
SELECT s.Sno, s.Sname
FROM Suppliers s
CROSS JOIN Parts p
LEFT JOIN Catalogue c ON s.Sno = c.Sno AND p.Pno = c.Pno
GROUP BY s.Sno, s.Sname
HAVING COUNT(*) = COUNT(c.Pno)
Try this:
alter proc clr
@c char(10),
@pno int output
as
begin
declare @f int
if exists(select p# from p where colour=@c)
begin
select @pno=p# from p where colour=@c
--set @f=1
end
-- else
-- set @f=0
-- return @f
end
--clr 'red',2
select p# from p where colour='red'
alter proc prcs
@c char(20)
as
begin
declare @pno numeric(2)
declare @f int
exec @f=clr @c,@pno output
--if @f=1
-- begin
select @pno
select s# from sp where p#=@pno
--set @i=1
-- end
--set @i=0
--return @i
end
prcs 'red'
select * from sp
select * from p,sp where p.p#=sp.p# and colour='red'
alter proc prcj
@c char(10)
as
begin
declare @i int
exec @i=prcs @c
if @i=1
begin
print'list of supplier'
select sname from s
where s#=@c
end
else
print'this record is not found'
end
精彩评论