如何找到供应商提供SQL供应商提供的所有零件的供应商编号?

时间:2018-05-19 07:08:28

标签: sql sql-server

我正在努力为供应商找到SNO,该供应商提供供应商提供的所有部件。

例如,我有

(S1, P1, 100), 
(S1, P2, 200), 
(S2, P1, 300), 
(S2, P2, 100),
(S3, P1, 400),
(S4, P1, 100), 
(S4, P2, 200)

所以我试图找到提供S2提供的所有零件的供应商的SNO而不是一个零件。因此,答案应该是S1& S4但我无法获得SQL查询来解决这个问题。我希望我能得到一些帮助。

2 个答案:

答案 0 :(得分:0)

这就是我取得成果的方式:

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

答案 1 :(得分:0)

您可以在没有临时表的情况下执行此操作。假设你的表中没有重复项:

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);

如果您想要完全相同(即,提供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);