Show Top 3 Suppliers by Product Count
Join our community on Telegram!
Join the biggest community of Pharma students and professionals.
Show Top 3 Suppliers by Product Count
Suppliers Table:
Products Table:
Query Explanation:
SELECT TOP 3
-
Returns only the top 3 rows from the result set.
-
Used in SQL Server to limit rows (use
LIMITin MySQL instead).
S.SupplierID, S.SupplierName
-
Fetches the supplier's ID and name from the
Suppliers2table.
COUNT(P.ProductID) AS ProductCount
-
Counts how many products each supplier has in the
Products4table. -
Gives the count a readable column name:
ProductCount.
FROM Suppliers2 S
-
Selects from the
Suppliers2table and uses aliasSfor simplicity.
JOIN Products4 P ON S.SupplierID = P.SupplierID
-
Performs an inner join between
Suppliers2andProducts4usingSupplierID. -
Only includes suppliers who have at least one product.
GROUP BY S.SupplierID, S.SupplierName
-
Groups the results by each supplier to calculate the total number of products they supplied.
ORDER BY ProductCount DESC
-
Sorts the result from the highest product count to the lowest.
SQL Query:
SELECT TOP 3
S.SupplierID,
S.SupplierName,
COUNT(P.ProductID) AS ProductCount
FROM
Suppliers S
JOIN
Products P ON S.SupplierID = P.SupplierID
GROUP BY
S.SupplierID, S.SupplierName
ORDER BY
ProductCount DESC;
Output:

