본문 바로가기

TIL 통합/SQL

1/21 - WHERE IN, HAVING 활용

SQL 카타

문제 104. 619. Biggest Single Number

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

오답

select max(num)
from mynumbers
group by num
having count(*) = 1

싱글인 숫자 다 나와뻘임. 아침이라 잠이 제대로 덜 깬듯ㅋㅋ

 

정답

select max(num) as num
from mynumbers
where num in (select num
              from mynumbers
              group by num
              having count(*)=1)

이미  수차례 복습해봤던 형식의 간단한 문제.

where in 으로 num에 대한 조건(중복되지 않음)을 걸어주고서, 그 중 최댓값만 출력해내면 되는 문제였다.

잠 덜 깼다고, 졸린다고 헷갈리지 않도록 기록!

 

 

 

문제 105. 1045. Customers Who Bought All Products : having 활용

 

LeetCode - The World's Leading Online Programming Learning Platform

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

 

select c.customer_id
from product p left join customer c using(product_key)
group by c.customer_id
having count(*) = (select count(product_key)
                   from product)

이렇게 하면 customer_id 중 모든 상품을 구매했으면서 동시에 각 상품을 중복으로 여러개 산 사람을 집계하지 못한다는 것을 간과했다.

 

정답

select customer_id
from customer
group by customer_id
having count(distinct product_key) = (select count(product_key) from product)

전에 group by와 having절에 다른 칼럼을 적었다가 불가능이라고 나왔던 것으로 기억해서 다른 방식만 생각하면서 한참을 쩔쩔매고 있었는데, 잘못 기억하고 있었던 것인지 슬쩍 solution을 봐보니 가능한 거였음.

group by로 그룹화한 칼럼에 딸려있는(?) 칼럼이면 having 절에 쓸 수 있다는 것을 제대로 깨달았다. 하