«   2024/06   »
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
Recent Posts
Today
Total
관리 메뉴

짜리몽땅 매거진

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

Data/SQL

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

쿡국 2024. 5. 8. 13:54

 

문제1.  레스토랑의 요일별 VIP

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

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

https://solvesql.com/problems/restaurant-vip/

 

https://solvesql.com/problems/restaurant-vip/

 

solvesql.com

 

정답 쿼리

select *
from tips
where total_bill in (select max(total_bill) from tips group by day)

 

문제 해설

 

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

where total_bill in (select max(total_bill) from tips group by day)

 

각 요일별로 그룹핑했을 때, 가장 높은 매출금액이 total_bill 칼럼에 입력되어야 하므로 서브쿼리를 사용해 max(total_bill)을 집계한다. 이에 해당되는 매출금액이 값에 들어가게 된다.


문제2.  가구 판매의 비중이 높았던 날 찾기

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

문제 정보 : 난이도 4 / 정답률 25.28%

https://solvesql.com/problems/day-of-furniture/

 

https://solvesql.com/problems/day-of-furniture/

 

solvesql.com

 

정답 쿼리

SELECT order_date
      ,count(distinct CASE WHEN category = "Furniture" THEN order_id END) as furniture
      ,round((count(distinct CASE WHEN category = "Furniture" THEN order_id END)/(count(distinct order_id)+0.00))*100,2) as furniture_pct
FROM records
GROUP BY order_date
HAVING COUNT(distinct order_id) >= 10
      AND furniture_pct >= 40
ORDER BY furniture_pct desc, order_date

 

문제 해설

 

1. 주요 포인트 1 - select절 집계함수

round((count(distinct CASE WHEN category = "Furniture" THEN order_id END)/(count(distinct order_id)+0.00))*100,2) as furniture_pct

 

총 매출 건수에서 카테고리가 'Furniture'인 주문 수의 비율을 계산하는 집계함수인데, 뒤 쪽에 입력된 +0.00을 추가하기 전까지 계속 값이 0으로만 출력되었다. 알아보니 0.00을 더해 실수로 만든 후에 계산해야 원하는 값을 얻을 수 있었다. 이외에도 cast함수를 이용해 소수점을 출력할 수 있다.

 

+ 추가 정답 쿼리

SELECT order_date
      ,count(distinct CASE WHEN category = "Furniture" THEN order_id END) as furniture
      ,round((count(distinct CASE WHEN category = "Furniture" THEN order_id END)/(count(distinct order_id)+0.00))*100,2) as furniture_pct
FROM records
where order_date in (select order_date from records group by order_date having count(distinct order_id)>=10)
GROUP BY order_date
HAVING furniture_pct >= 40
ORDER BY furniture_pct desc, order_date

 

having에 적혀있었던 count(distinct order_id) >= 10 을 where절 서브쿼리를 이용해 동일한 결과를 출력할 수 있다.