오랑우탄의 반란

HackerRank | SQL Project Planning (MySQL) 본문

SQL/HackerRank

HackerRank | SQL Project Planning (MySQL)

5&2 2024. 10. 2. 10:42
반응형

 

오늘도 오랑이는 문제를 풉니다. 

 

 

SQL Project Planning

You are given a table, Projects, containing three columns: Task_ID, Start_Date and End_Date. It is guaranteed that the difference between the End_Date and the Start_Date is equal to 1 day for each row in the table.
If the End_Date of the tasks are consecutive, then they are part of the same project. Samantha is interested in finding the total number of different projects completed.
Write a query to output the start and end dates of projects listed by the number of days it took to complete the project in ascending order. If there is more than one project that have the same number of completion days, then order by the start date of the project.

 

Sample Input

Sample Output

2015-10-28 2015-10-29
2015-10-30 2015-10-31
2015-10-13 2015-10-15
2015-10-01 2015-10-04

 

 

풀이 과정

start_date와 end_date가 같은 경우 = 하나의 프로젝트이기 때문에, 이 경우를 제외한 행들의 start_date와 end_date를 구해야 합니다. 각각의 조건이 겹치기 때문에 두 칼럼을 분리해서 조회해야 하고, 이를 이어줄 칼럼을 새로 생성해야 합니다. 

 

먼저 start_date 테이블을 만들어줍니다. 

row_number를 사용해 r1이라는 칼럼을 생성해 프로젝트 시작일을 나열해줍니다. 

WITH SD AS (
    SELECT START_DATE, ROW_NUMBER() OVER (ORDER BY START_DATE) AS R1
    FROM PROJECTS
    WHERE START_DATE NOT IN (SELECT END_DATE FROM PROJECTS)
)

 

마찬가지로 end_date 테이블을 만들어주고 두 테이블을 각각 조회해보면 r1, r2가 연결되어 하나의 행으로 통일할 수 있는 것을 볼 수 있습니다. 

ED AS (
    SELECT END_DATE, ROW_NUMBER() OVER (ORDER BY END_DATE) AS R2
    FROM PROJECTS
    WHERE END_DATE NOT IN (SELECT START_DATE FROM PROJECTS)
)

 

 

이제 메인 쿼리에서 두 테이블을 join 하고 정렬에서 datediff 로 프로젝트 일수를 구해줍니다. 

 

최종 쿼리

WITH SD AS (
    SELECT START_DATE, ROW_NUMBER() OVER (ORDER BY START_DATE) AS R1
    FROM PROJECTS
    WHERE START_DATE NOT IN (SELECT END_DATE FROM PROJECTS)
),
ED AS (
    SELECT END_DATE, ROW_NUMBER() OVER (ORDER BY END_DATE) AS R2
    FROM PROJECTS
    WHERE END_DATE NOT IN (SELECT START_DATE FROM PROJECTS)
)
SELECT START_DATE, END_DATE
FROM SD JOIN ED ON SD.R1=ED.R2
ORDER BY DATEDIFF(END_DATE,START_DATE), START_DATE

 

 

 

오랑우탄이 영어를 하고 오랑이가 쿼리마스터가 되는 그날까지~

 

 

 

 

SQL Project Planning | HackerRank

Write a query to output the start and end dates of projects listed by the number of days it took to complete the project in ascending order.

www.hackerrank.com

 

반응형