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.
Python Practice Questions & Solutions Day 5 of Learning Python for Data Science Welcome back…
Day 5 of Learning Python for Data Science: Data Types, Typecasting, Indexing, and Slicing Understanding…
Python Practice Questions & Solutions Day 4 of Learning Python for Data Science Welcome back…
Day 4 of Learning Python for Data Science Day 4 of Learning Python for Data…
Test your Python skills with these 20 practice questions and solutions from Day 3 of…
Understanding Python’s conditional statements is essential for controlling the flow of a program. Today, we…