Reputation: 433
I've been given a question using AdventureWorks to list all the vendors with no products. When I run my SELECT statement nothing is returned. What am I doing wrong? (Answer can only be done using Joins and Unions - No Subqueries)
SELECT DISTINCT pv.Name AS 'Vendors'
FROM Purchasing.Vendor pv
INNER JOIN Purchasing.ProductVendor ppv
ON pv.BusinessEntityID = ppv.BusinessEntityID
INNER JOIN Production.Product pp
ON pp.ProductID = ppv.ProductID
WHERE pp.ProductID != ppv.ProductID;
Upvotes: 2
Views: 1501
Reputation: 28854
COUNT()
function.HAVING
clause Try the following:
SELECT pv.Name AS 'Vendors',
Count(pp.ProductID) AS count_products
FROM Purchasing.Vendor pv
LEFT JOIN Purchasing.ProductVendor ppv
ON pv.BusinessEntityID = ppv.BusinessEntityID
LEFT JOIN Production.Product pp
ON pp.ProductID = ppv.ProductID
GROUP BY pv.Name
HAVING count_products = 0;
Upvotes: 1
Reputation: 4960
You're looking at one too many tables, all ProductVendors have Products. Not all Vendors have ProductVendors.
From there you can simply use a LEFT JOIN
and look for null records.
SELECT DISTINCT v.Name
FROM Purchasing.Vendor v
LEFT JOIN Purchasing.ProductVendor pv ON pv.BusinessEntityID = v.BusinessEntityID
WHERE pv.BusinessEntityID IS NULL
Upvotes: 3
Reputation: 65
SELECT DISTINCT pv.Name AS 'Vendors'
FROM Purchasing.Vendor pv
INNER JOIN Purchasing.ProductVendor ppv
ON pv.BusinessEntityID = ppv.BusinessEntityID
where not exists (SELECT 1 Production.Product pp Where pp.ProductID = ppv.ProductID)
Return all vendors wich donot have any product
Upvotes: -1