«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Recent Posts
Today
Total
관리 메뉴

짜리몽땅 매거진

[SQL] solvesql 코딩테스트 연습4 본문

Data/SQL

[SQL] solvesql 코딩테스트 연습4

쿡국 2024. 4. 9. 01:46

 

문제1.  레스토랑의 대목

출처 : solvesql 데이터리안 sql 캠프 실전반

문제 정보 : 난이도 2 / 정답률 61.07%

https://solvesql.com/problems/high-season-of-restaurant/

 

정답 쿼리

select *
from tips
where day in (select day
              from tips
              group by day
              having sum(total_bill)>1500)

 

문제 해설

 

1. 주요 포인트 1 - where절 서브쿼리

where day in (select day
              from tips
              group by day
              having sum(total_bill)>1500)

 

insert절의 스칼라 서브쿼리, from절의 인라인뷰, where절의 일반 서브쿼리로 분류되는 서브쿼리를 where절에 적용한 사례이다. 요일 별로 그룹핑했을 때, 총 계산 금액 합계가 1500달러 이상인 요일만을 선택하는 쿼리를 먼저 작성 후, 메인 쿼리의 where 절로 필터링을 해준다. 만약 서브쿼리를 사용하지 않고 아래와 같이 작성할 경우, 레코드(행)의 개수가 결과 값과 다르게 나오는 오류가 발생한다.

SELECT SUM(total_bill), tip, sex, smoker, day, time, size
FROM tips
GROUP BY day
HAVING SUM(total_bill) > 1500;

문제2.  지역별 주문의 특징

출처 : solvesql 데이터리안 sql캠프 입문반

문제 정보 : 난이도 3 / 정답률 28.07%

https://solvesql.com/problems/characteristics-of-orders/

 

정답 쿼리

select region as Region,
count(distinct(case when category = 'Furniture' then order_id end)) as Furniture,
count(distinct(case when category = 'Office Supplies' then order_id end)) as 'Office Supplies',
count(distinct(case when category = 'Technology' then order_id end)) as Technology
from records
group by Region
order by Region

 

문제 해설

 

1. 주요 포인트 1 - count distinct, case when then

count(distinct(case when category = 'Furniture' then order_id end)) as Furniture,
count(distinct(case when category = 'Office Supplies' then order_id end)) as 'Office Supplies',
count(distinct(case when category = 'Technology' then order_id end)) as Technology

 

지역 별로 furniture, office supplies, technology 카테고리의 제품이 몇 개씩 주문되었는지 작성해야 하므로, 먼저 case when then 구문을 활용해 각 카테고리를 구분해준 뒤, order_id 를 중복되지 않게 카운팅해 정확한 주문량이 출력되도록 한다.