[英]How to find the Supplier number for those suppliers who supply all parts that are supplied by another by supplier in SQL?
I am trying to find the SNO for the Supplier that supplied all parts that is supplied that by another by Supplier. 我正在寻找供应商的SNO,该供应商提供了由供应商提供的所有零件。
For example, I have 例如,我有
(S1, P1, 100),
(S1, P2, 200),
(S2, P1, 300),
(S2, P2, 100),
(S3, P1, 400),
(S4, P1, 100),
(S4, P2, 200)
So I am trying to find the SNO of the suppliers that supplied all the parts supplied by S2 not one part. 因此,我试图找到提供S2提供的所有零件的供应商的SNO,而不是一个零件。 Therefore, the answer should be S1 & S4 but I could not get the SQL Query to solve this. 因此,答案应该是S1和S4,但我无法通过SQL查询来解决此问题。 I hope I could get some help. 希望我能有所帮助。
this is how I achieved the result: 这是我达到结果的方式:
create table MyTable (
Supplier varchar(20),
Part varchar(20),
SomeOrder int
)
insert into MyTable values
('S1', 'P1', 100),
('S1', 'P2', 200),
('S2', 'P1', 300),
('S2', 'P2', 100),
('S3', 'P1', 400),
('S4', 'P1', 100),
('S4', 'P2', 200)
---------------------------
-- temporary table to store all parts of a supplier
CREATE TABLE #tmp (Part varchar(20))
-- put your desired provider here
declare @Supplier varchar(20) = 'S2'
-- select all parts of this supplier
insert into #tmp
select Part from MyTable where Supplier = @Supplier
-- count how many parts this supplier has
declare @partCount int
select @partCount = count(*) from #tmp
-- select all suppliers that have all the parts (i.e. count = @partCount)
select innerTbl.Supplier from (
select m.Supplier, m.Part
from MyTable m
inner join #tmp t on t.Part = M.Part
) innerTbl
group by innerTbl.Supplier
having Count(innerTbl.Supplier) = @partCount
and innerTbl.Supplier <> @Supplier
You can do this without temporary tables. 您可以在没有临时表的情况下执行此操作。 Assuming there are no duplicates in your table: 假设表中没有重复项:
select sp.supplier
from supplierparts sp join
supplierparts sp2
on sp.part = sp2.part and sp2.supplier = 2
group by sp.supplier
having count(*) = (select count(*) from supplierparts sp3 where sp3.supplier = 2);
If you wanted exact equality (that is, supplying P3
would invalidate the supplier), then: 如果您想要完全相等(即,提供P3
将使供应商无效),则:
select sp.supplier
from supplierparts sp left join
supplierparts sp2
on sp.part = sp2.part and sp2.supplier = 2
group by sp.supplier
having count(*) = (select count(*) from supplierparts sp3 where sp3.supplier = 2) and
count(*) = count(sp2.part);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.