hdonghun / SQL

1 stars 0 forks source link

SQL 문제 풀기_ HACKER RANK - SQL Project Planning #39

Open hdonghun opened 2 years ago

hdonghun commented 2 years ago

HACKER RANK - SQL Project Planning 출처 : https://www.inflearn.com/course/sql-%EA%B3%A0%EA%B8%89-%EB%AC%B8%EC%A0%9C%ED%92%80%EC%9D%B4/lecture/66115?tab=curriculum

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. image

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 : image

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

Explanation

The example describes following four projects:

Project 1: Tasks 1, 2 and 3 are completed on consecutive days, so these are part of the project. Thus start date of project is 2015-10-01 and end date is 2015-10-04, so it took 3 days to complete the project. Project 2: Tasks 4 and 5 are completed on consecutive days, so these are part of the project. Thus, the start date of project is 2015-10-13 and end date is 2015-10-15, so it took 2 days to complete the project. Project 3: Only task 6 is part of the project. Thus, the start date of project is 2015-10-28 and end date is 2015-10-29, so it took 1 day to complete the project. Project 4: Only task 7 is part of the project. Thus, the start date of project is 2015-10-30 and end date is 2015-10-31, so it took 1 day to complete the project.

hdonghun commented 2 years ago

MySQL : SELECT start_date, end_date FROM( SELECT start_date, ROW_NUMBER() OVER(ORDER BY start_date) rnk FROM PROJECTS WHERE start_date NOT IN (SELECT DISTINCT end_date FROM PROJECTS) ) s_date INNER JOIN ( SELECT end_date, ROW_NUMBER() OVER(ORDER BY end_date) rnk FROM PROJECTS WHERE end_date NOT IN (SELECT DISTINCT start_date FROM PROJECTS) ) e_date ON s_date.rnk = e_date.rnk ORDER BY DATEDIFF(end_date, start_date), start_date

hdonghun commented 2 years ago

DateDiff 함수 : DATEDIFF ( datepart , startdate , enddate )
이 기능은 지정된 startdate 와 enddate 사이에 지정된 datepart 경계의 수(부호 있는 정수 값으로)를 반환합니다.