0

I am newbie in mysql, for learning i am using sample database of w3schools. in that i want to create a view which will for each supplier, list the supplier name, the count of distinct products by the supplier (PCount), the count of distinct product categories by the supplier (CCount).

here is my table structures

Suppliers                             Products
--------------------            ----------------------------
SupplierID                             ProductID
SupplierName                           ProductName  
ContactNumber                          SupplierID
Address                                CategoryID
City                                   Unit  
PostalCode                             Price
Country
Phone

What i have try is

SELECT s.SupplierName, COUNT(DISTINCT(p.ProductID)) as PCount, COUNT(DISTINCT(p.CategoryID)) as CCount FROM Suppliers as s 
right join Products as p 
on s.SupplierID = p.SupplierID

this is only giving me single SupplierName not all the supplier details with distinct product and distinct category.

Any help would be much appreciated.

Nigel Ren
  • 56,122
  • 11
  • 43
  • 55
cooldev
  • 47
  • 7
  • You need to `GROUP BY s.SupplierName` – Nick Apr 26 '20 at 06:20
  • The duplicate uses a different aggregate function (`GROUP_CONCAT` versus `COUNT`) but the principle is the same – Nick Apr 26 '20 at 06:22
  • @Nick i did not get your last comment.! you mean to say i can use any one of them.? – cooldev Apr 26 '20 at 06:26
  • No, what I meant was that the reason the query in the duplicate didn't give the expected result was due to the lack of the `GROUP BY` clause, and that is the same reason that your query doesn't give the expected result. – Nick Apr 26 '20 at 06:56

1 Answers1

0

Give this a shot:

SELECT s.SupplierName,
    COUNT(p1.ProductID) AS PCount,
    COUNT(DISTINCT p2.CategoryID) AS CCount
FROM Suppliers s
    LEFT JOIN Products p1 ON s.SupplierID=p1.SupplierID
    LEFT JOIN Products p2 ON s.SupplierID=p2.SupplierID
GROUP BY s.SupplierName
ORDER BY s.SupplierName
Tripp Kinetics
  • 5,178
  • 2
  • 23
  • 37