SELECT product_id
FROM sales
GROUP BY product_id
HAVING COUNT(DISTINCT region_id) = (SELECT COUNT(*) FROM regions);
We need to find products that have been sold in all regions. This involves comparing the distinct regions a product appears in with the total number of regions available. Here’s how the query works step-by-step:
(SELECT COUNT(*) FROM regions)
regions
table.5
.SELECT product_id FROM sales GROUP BY product_id
sales
table is grouped by product_id
, so each group represents a single product and its associated sales records.product_id
, we count the distinct region_id
values to determine how many unique regions that product has been sold in.HAVING COUNT(DISTINCT region_id) = (SELECT COUNT(*) FROM regions)
HAVING
clause filters the results to include only those products for which the number of distinct regions matches the total number of regions from the subquery.product_id | region_id |
---|---|
1 | 1 |
1 | 2 |
2 | 1 |
2 | 2 |
2 | 3 |
3 | 1 |
region_id |
---|
1 |
2 |
3 |
SELECT COUNT(*) FROM regions
→ Returns 3
.product_id |
---|
2 |
Hi, I am Vishal Jaiswal, I have about a decade of experience of working in MNCs like Genpact, Savista, Ingenious. Currently i am working in EXL as a senior quality analyst. Using my writing skills i want to share the experience i have gained and help as many as i can.
Welcome to Day 13 of Learning Python for Data Science! Today, we’re focusing on three…
Test your understanding of Python Data Structure, which we learned in our previous lesson of…
Welcome to Day 12 of Learning Python for Data Science. Today, we’ll dive into Pandas,…
NumPy Array in Python is a powerful library for numerical computing in Python. It provides…
Welcome to Day 9 of Learning Python for Data Science. Today we will explore comprehensions,…
Test your understanding of Python Data Structure, which we learned in our previous lesson of…