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.
SQL Interview Question at Zomato: These questions were recently asked in interview at Zomato, you…
Introduction: SQL Indexing and Query Optimization SQL indexing is a critical concept that can drastically…
This article is about the SQL Interview Questions asked by Walmart for their Data Analyst…
You must be able to answer these SQL Interview Questions if you are applying for…
This article tackles common SQL Interview Questions asked by EY, offering detailed solutions and explanations…
1164. Product Price at a Given Date: Learn how to track and select price from…