출처
문제
2019년의 1/4에만 판매된 제품을 보고하는 솔루션을 작성합니다. 즉, 2019-01-01~ 019-03-31 사이
문제에 대한 해석
![]() |
![]() |
![]() |
Sales테이블에서 2019년 1분기에만 판매된 제품의id와 이름을 조회하는 것으로
2019년 1분기외 판매된 적이 없어야 한다(이전, 이후)
또한 출력값은 중복값이 없어야 한다
풀이(MYSQL)
select distinct(a.product_id), a.product_name
from Product a
join
(select product_id
from Sales
where sale_date between '2019-01-01' and '2019-03-31'
and product_id not in(select product_id from Sales where sale_date > '2019-03-31' or sale_date < '2019-01-01'))b
on a.product_id = b.product_id
작동순서
💡SQL 실행 순서는 From -> Where -> Group by -> Having -> Select -> Order by ->결과반환
- FROM 절: Sales 테이블에서
- sale_date가 '2019-01-01'와 '2019-03-31'사이이면서
- sale_date가'2019-03-31' 보다 이후인 product_id가 아니고
- sale_date가' 2019-01-01 ' 보다 이전인 product_id가 아닌 경우의 product_id를 조회한 테이블과 Product 테이블을 product_id를 기준으로 조인하여
- SELECT 절: product_id의 고유값과 그에따른 product_name을 출력하라
다른사람 풀이
select p.product_id, p.product_name
from product p join sales s
on p.product_id = s.product_id
group by product_id
having min(sale_date)>='2019-01-01' and max(sale_date)<='2019-03-31'
product_id를 기준으로 그룹화 했을 때 sale_date의 최솟값이 2019-01-01이상이고 sale_date의 최대값이 2019-03-31이하인 경우 필터링
배운점
날짜를 사용할때 문자열의 형식으로 작성
'문제풀이 > SQL(My sql)' 카테고리의 다른 글
[문제풀이] Leet code - Delete Duplicate Emails (0) | 2024.08.06 |
---|---|
[문제풀이] Leet code - Market Analysis I (0) | 2024.08.02 |
[문제풀이] Leet code - Product Sales Analysis III (0) | 2024.08.01 |
[문제풀이] Leet code - Customers Who Bought All Products (0) | 2024.07.31 |
[문제풀이] Leet code - Exchange Seats (0) | 2024.07.31 |