Study - Problems(IT)/LeetCode - SQL

1045.Customers Who Bought All Products

Dev.D 2024. 11. 26. 23:11

* Problems

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.

Input: 
Customer table:
+-------------+-------------+
| customer_id | product_key |
+-------------+-------------+
| 1           | 5           |
| 2           | 6           |
| 3           | 5           |
| 3           | 6           |
| 1           | 6           |
+-------------+-------------+
Product table:
+-------------+
| product_key |
+-------------+
| 5           |
| 6           |
+-------------+
Output: 
+-------------+
| customer_id |
+-------------+
| 1           |
| 3           |
+-------------+

 

* Explanation

The customers who bought all the products (5 and 6) are customers with IDs 1 and 3.

 

* Solution (Success)

# Write your MySQL query statement below
SELECT customer_id
    FROM Customer
    GROUP BY 1
    HAVING COUNT(DISTINCT product_key) = (
        SELECT COUNT(*) FROM Product
    );
 

 

* Tips

- Group by 1

- Product  대상 데이터의 수량을 customer 테이블에서 각 id마다 수량을 지니고 있는지를 조회하는 query