코딩일기
SQL 코드카타 105 - Customers Who Bought All Products
서재일
2024. 7. 2. 12:16
https://leetcode.com/problems/find-followers-count/description/
Column Name | Type |
customer_id | int |
product_key | int |
Followers 테이블:
- customer_id (int): 고객 ID
- product_key (int): 제품 키 (고객이 구매한 제품)
Column Name | Type |
product_key | int |
Product테이블:
- product_key (int): 제품 키 (고유키)
모든 제품을 구매한 고객의 ID를 출력하세요.
원래는 서브쿼리를 만들어서 풀려고 했지만 오늘은 HAVING절을 연습해보기로 했다. 그동안 sql문제를 풀면서 HAVING을 제대로 사용해본 적이 별로 없었기 때문이다.
SELECT COUNT(*)
FROM Product
먼저 product_key의 원소 갯수를 세어준다. 이 원소의 갯수와 각 custome가 구매한 상품의 갯수가 일치하면 된다.
select *
from Customer
group by customer_id
메인쿼리를 만들고 customer_id로 그룹화해준다.
select *
from Customer
group by customer_id
HAVING (count(product_key)) = (select count(*) from Product)
HAVING절을 추가하고 그룹별로 product_key의 갯수를 세어준다. 그리고 위에서 구했던 product_key의 원소 갯수와 일치하는 행만 출력한다.
select customer_id
from Customer
group by customer_id
HAVING (count(product_key)) = (select count(*) from Product)
하지만 오류가 발생했다.. 생각해보니 한 고객이 같은 상품을 여러번 구매하는 경우를 고려하지 못했다.
select customer_id
from Customer
group by customer_id
HAVING (count(DISTINCT product_key)) = (select count(*) from Product)
product_key에 DISTINCT를 추가해서 중복값을 또 세는것을 방지했다.
문제 자체는 어렵지 않았지만 덕분에 평소에 잘 사용하지 않았던 HAVING을 연습해볼 수 있었다.