0

Consider the schema with the tables :

Products

enter image description here

And Family

enter image description here

How can I get the number of products of each family_code ?

This :

SELECT count(family_code)
FROM products;

returns the number of family_code record in the Products table ,how can I alter that to find each family_code with its number of products ?

Thanks

For instance

enter image description here

1234 has 2

2345 has 1

12345 has 1

2 Answers 2

1

By starting with the family table and LEFT JOINing to the products table, this will list all family codes, regardless if they are in the product table or not (i.e., it will list families that have no products)

SELECT f.family_code,f.family_name, COUNT(p.prod_id) AS number_of_products
FROM family AS f
LEFT JOIN products AS p
 ON f.family_code = p.family_code
GROUP BY f.family_code, family_name;
Sign up to request clarification or add additional context in comments.

Comments

1

Use COUNT(*) grouped by family_code:

select family_code, count(*) product_count
from products
group by family_code

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.