Welcome Back

Google icon Sign in with Google
OR
I agree to abide by Pharmadaily Terms of Service and its Privacy Policy

Create Account

Google icon Sign up with Google
OR
By signing up, you agree to our Terms of Service and Privacy Policy
Instagram
youtube
Facebook

Show Top 3 Suppliers by Product Count

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 LIMIT in MySQL instead).

S.SupplierID, S.SupplierName

  • Fetches the supplier's ID and name from the Suppliers2 table.

COUNT(P.ProductID) AS ProductCount

  • Counts how many products each supplier has in the Products4 table.

  • Gives the count a readable column name: ProductCount.

FROM Suppliers2 S

  • Selects from the Suppliers2 table and uses alias S for simplicity.

JOIN Products4 P ON S.SupplierID = P.SupplierID

  • Performs an inner join between Suppliers2 and Products4 using SupplierID.

  • 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: