diff --git a/README.md b/README.md index 8161efa..f4af00f 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ Have a good contributing! 2. [Medium](./leetcode/medium/) - [176. Second Highest Salary](./leetcode/medium/176.%20Second%20Highest%20Salary.sql) - [184. Department Highest Salary](./leetcode/medium/184.%20Department%20Highest%20Salary.sql) + - [1045. Customers Who Bought All Products](./leetcode/medium/1045.%20Customers%20Who%20Bought%20All%20Products.sql) - [1070. Product Sales Analysis III](./leetcode/medium/1070.%20Product%20Sales%20Analysis%203.sql) - [1158. Market Analysis 1](./leetcode/medium/1158.%20Market%20Analysis%201.sql) diff --git a/leetcode/medium/1045. Customers Who Bought All Products.sql b/leetcode/medium/1045. Customers Who Bought All Products.sql new file mode 100644 index 0000000..73450c9 --- /dev/null +++ b/leetcode/medium/1045. Customers Who Bought All Products.sql @@ -0,0 +1,46 @@ +/* +Question 1045. Customers Who Bought All Products +Link: https://leetcode.com/problems/customers-who-bought-all-products/description/ + +Table: Customer + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| customer_id | int | +| product_key | int | ++-------------+---------+ +This table may contain duplicates rows. +customer_id is not NULL. +product_key is a foreign key (reference column) to Product table. + + +Table: Product + ++-------------+---------+ +| Column Name | Type | ++-------------+---------+ +| product_key | int | ++-------------+---------+ +product_key is the primary key (column with unique values) for this table. + + +Write a solution to report the customer ids from the Customer table that bought all the products in the Product table. + +Return the result table in any order. +*/ + +WITH Customer_products AS ( + SELECT + customer_id, + COUNT(DISTINCT product_key) AS c + FROM Customer + GROUP BY customer_id +) + +SELECT customer_id +FROM Customer_products +WHERE c = ( + SELECT COUNT(1) + FROM Product +)