SQL - 문제 풀이

hyun-jin·2025년 3월 19일

데이터 분석

목록 보기
23/100
post-thumbnail

데이터 분석 21일차


https://leetcode.com/problems/not-boring-movies/description/

  • 홀수(odd) 라는것에 나머지가 1인 숫자를 구하면 되겠지라 생각하고 그럼 1은? 하고 짠 코드가...
    where id = 1 or id % 2 = 1 and description != 'boring'
    id=1은 필요가 없다.

✅정답 코드

select *
from cinema 
where id % 2 = 1 and description != 'boring'
order by rating desc

https://leetcode.com/problems/average-selling-price/

✔️ 중요 포인트!
- start_date과 end_date 날짜사이에 포함된 UnitsSold 테이블의 Purchase_date가 들어가야함.
- 결과에서 average_price에 null일 경우 0을 넣어주기

--> 내가 푼거

with avg_price as (select p.product_id, 
       round((SUM(units*price)/SUM(units)),2) average_price
from prices p left join unitssold u on p.product_id = u.product_id 
     and u.purchase_date between start_date and end_date
group by p.product_id)
#
select product_id, 
       case when average_price is null then 0 else average_price end average_price
from avg_price

평균 구해준 걸 with문으로 해서 다시 average_price가 null일때 0 넣는 조건을 줘서 추출해줌.

💡더 좋은 방법! - ifnull() 쓰는 방법이 있다.

  • ifnull 구조: IFNULL(조건, 0)
    - 조건의 결과가 만약 null일 경우 0을 넣어줘

✅ 더 간단한 코드

  • 이러면 두번 select 하지 않아도 된다.

💭 SQL은 문제를 풀면 풀수록 계속 새로운걸 배우게 되는 것 같다.

0개의 댓글