[HackerRank lv4] SQL문제풀이 - SQL Project Planning(Oracle)

데프·2023년 11월 26일
0

SQL문제풀이

목록 보기
5/7

👉 문제 바로가기(HackerRank)
Question.
start_dateend_date가 주어질 때, 날짜가 연속되면 같은 프로젝트이다. 프로젝트 단위로 start_dateend_date를 출력하고.
프로젝트별 기간이 오래걸린 순서대로, 걸린 기간이 같다면 start_date로 정렬하라.
ex)

INPUT OUTPUT
startend
2015-10-012015-10-02
2015-10-022015-10-03
2015-10-032015-10-04
2015-10-052015-10-06
2015-10-062015-10-07
2015-10-082015-10-09
startend
2015-10-012015-10-04
2015-10-052015-10-07
2015-10-082015-10-09

문제를 딱 보고 떠오른 생각은 '계층형 쿼리'를 써야하나?
그런데 막상 써보니 안될 것 같다.

lag() over()를 써야하나?
이 또한 작성해보니 안될 것 같다.

그럼 어떻게 🤷‍..❓

# 정답

# oracle
with start_list(rn, start_date) as (
    select row_number() over (order by start_date), start_date
    from projects
    where start_date not in (select end_date from projects)
    order by start_date
), end_list(rn, end_date) as (
    select row_number() over (order by start_date), end_date
    from projects
    where end_date not in (select start_date from projects)
    order by start_date
)
select 
    start_date
    , end_date
from 
    start_list s
    , end_list e
where
    s.rn = e.rn
order by
    end_date - start_date
    , start_date
;

# 풀이

고민 끝에 알아낸 것은 프로젝트 시작일프로젝트 종료일을 알 수 있다는 것이다.
정확히는 프로젝트 기간 중간에 속하는 start_dateend_date는 개수가 여러개다!

위의 예시에서 2015-10-01은 첫행에만 존재하지만 2015-10-02, 2015-10-03같은 날짜들은 두개씩 존재한다.

이것을 바탕으로 not in 조건을 걸어서 문제를 해결하였다.
프로젝트 각각의 시작일, 종료일을 구할수만 있다면 그 뒤는 조인하여 출력하면 되는 쉽지만 발상하기가 어려울 수 있는 문제

profile
정보의 홍수를 기록하는 데프의 로그

0개의 댓글

관련 채용 정보