这正是您所要求的:
SELECT
S.SupplierID,
S.sName
FROM
dbo.Suppliers S
WHERE
EXISTS (
SELECT *
FROM dbo.SPJ SPJ
WHERE S.SupplierID = SPJ.SupplierID
GROUP BY SPJ.PartID
HAVING Count(*) >= 2
);
请参阅我的 SQLFiddle以在真实数据集上进行尝试。请注意,还有一个查询显示参与使供应商符合条件的所有单独行(请参见Qualifies
列)。这是安装脚本的预览:
CREATE TABLE dbo.Suppliers (
SupplierID smallint identity(1,1) NOT NULL CONSTRAINT PK_Suppliers PRIMARY KEY CLUSTERED,
sName varchar(40) NOT NULL CONSTRAINT UQ_Suppliers_sName UNIQUE
);
CREATE TABLE dbo.Parts (
PartID int identity(1,1) NOT NULL CONSTRAINT PK_Parts PRIMARY KEY CLUSTERED,
pName varchar(100) NOT NULL CONSTRAINT UQ_Parts_pName UNIQUE
);
CREATE TABLE dbo.Projects (
ProjectID int identity(1,1) NOT NULL CONSTRAINT PK_Projects PRIMARY KEY CLUSTERED,
jName varchar(50) NOT NULL CONSTRAINT UQ_Projects_jName UNIQUE
);
CREATE TABLE dbo.SPJ (
SupplierID smallint NOT NULL CONSTRAINT FK_SPJ_Suppliers FOREIGN KEY REFERENCES dbo.Suppliers (SupplierID),
PartID int NOT NULL CONSTRAINT FK_SPJ_Parts FOREIGN KEY REFERENCES dbo.Parts (PartID),
ProjectID int NOT NULL CONSTRAINT FK_SPJ_Projects FOREIGN KEY REFERENCES dbo.Projects (ProjectID),
CONSTRAINT PK_SPJ PRIMARY KEY CLUSTERED (SupplierID, PartID, ProjectID)
);
INSERT dbo.Suppliers
VALUES
('Joe'' Specialty Goods'),
('Major Supplier'),
('Small Supplier'),
('Tamandua Manufacturing, Ltd.'),
('Things ''n'' Stuff'),
('Stuff ''n'' Things');
INSERT dbo.Parts
VALUES
('Watchamacallit'),
('Thingamajiggy'),
('Thingamabob'),
('Doohickey'),
('Whatsisname'),
('Thingy'),
('Gizmo'),
('Gadget'),
('Widget'),
('Titanium Widget'),
('Electronic Thingamabob'),
('One-Product Patrick');
INSERT dbo.Projects
VALUES
('Video Game Manufacturing'),
('Autodoc Research'),
('Consumer Electronics Expansion'),
('Space Shuttle'),
('Tablet Project Cobalt');
INSERT dbo.SPJ
VALUES
(1, 2, 1),
(1, 3, 1),
(1, 7, 1),
(1, 11, 1),
(2, 1, 1),
(2, 1, 2),
(2, 1, 3),
(2, 1, 4),
(2, 2, 1),
(2, 2, 2),
(2, 2, 3),
(2, 2, 4),
(2, 2, 5),
(2, 10, 1),
(2, 10, 2),
(2, 10, 3),
(2, 10, 4),
(2, 10, 5),
(3, 5, 4),
(4, 4, 2),
(4, 4, 3),
(5, 9, 1),
(5, 8, 2),
(5, 7, 3),
(5, 6, 4),
(5, 5, 5),
(6, 1, 1),
(6, 2, 1),
(6, 3, 1),
(6, 4, 1),
(6, 5, 1),
(6, 6, 1),
(6, 7, 1),
(6, 8, 1),
(6, 9, 1),
(6, 10, 1),
(6, 11, 1);