SQL

[leetCode] #197 (날짜 차이 계산하기/TO_DAYS, DATEDIFF, SUBDATE)

빛날희- 2023. 8. 6. 22:30

문제 - Rising Temperature

https://leetcode.com/problems/rising-temperature/

 

Rising Temperature - LeetCode

Can you solve this real interview question? Rising Temperature - Table: Weather +---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+ id is the pr

leetcode.com

Find all dates' Id with higher temperatures compared to its previous dates (yesterday).

Return the result table in any order.

 

작성 답안

select w1.id
from weather as w1, weather as w2
where datediff(w1.recordDate, w2.recordDate) = 1 and w2.temperature < w1.temperature

- 하나의 테이블을 두번 활용함으로써 각 행의 값들을 비교할 수 있도록 한다.

- datediff 로 w1의 recordDate와 차이가 1인 행들만 추출한다.

- w1의 temparature보다 낮은 temperature를 가진 행들만 추출한다.

 

리뷰

DATEDIFF(date1, date2)

- date1과 date2 간의 날짜차이(일수 기준)를 반환한다.

 

discussion의 답안 중 to_days를 활용해 날짜 차이를 구하는 답안도 있었다.

# https://leetcode.com/problems/rising-temperature/discuss/55619/Simple-Solution
SELECT wt1.Id 
FROM Weather wt1, Weather wt2
WHERE wt1.Temperature > wt2.Temperature AND 
      TO_DAYS(wt1.DATE)-TO_DAYS(wt2.DATE)=1;

TO_DAYS(date)

- date와 year 0("0000-00-00")간의 일 수를 반환한다.

- 그레고리안 달력 내 날짜에 한해서만 사용할 수 있다.

- 반대 함수는 FROM_DAYS(number)이다.

 

date에서 특정 날짜만큼 빼는 subdate 함수도 활용할 수 있다.

# https://leetcode.com/problems/rising-temperature/discuss/2386995/Three-different-solutions-oror-datediff-and-subdate
SELECT w2.id from Weather w1, Weather w2
WHERE w2.temperature > w1.temperature AND
subdate(w2.recordDate, 1) = w1.recordDate;

 

SUBDATE(date, INTERVAL value unit)

- date에서 INTERVAL만큼 뺀 날짜를 반환한다.

- unit에는 다음과 같은 시간 혹은 날짜 기준 단위가 사용될 수 있다. (default는 day이다)

 

'SQL' 카테고리의 다른 글

[leetCode] #1661  (0) 2023.08.07
[leetCode] #1581 (EXISTS)  (0) 2023.08.03
[leetCode] # 1378  (0) 2023.08.01
[leetCode] #1683 (length와 char_length의 차이)  (0) 2023.07.31
[leetCode] #1148 (쿼리실행순서)  (0) 2023.07.19