문제 설명
- 테이블 명 : Weather
+---------------+---------+ | Column Name | Type | +---------------+---------+ | id | int | | recordDate | date | | temperature | int | +---------------+---------+
- 테이블 설명 :
id는 고유 값이 있는 column이다.
동일한 recordDate를 가진 다른 row는 없다.
이 테이블에는 특정 날짜의 기온에 대한 정보가 포함되어 있다.
- 문제 :
이전 날짜(어제)에 비해 온도가 더 높은 모든 날짜의 id를 찾는 솔루션을 작성하라.
순서 상관 없이 결과를 반환한다.
입출력 예시
Input: Weather table: +----+------------+-------------+ | id | recordDate | temperature | +----+------------+-------------+ | 1 | 2015-01-01 | 10 | | 2 | 2015-01-02 | 25 | | 3 | 2015-01-03 | 20 | | 4 | 2015-01-04 | 30 | +----+------------+-------------+ Output: +----+ | id | +----+ | 2 | | 4 | +----+
- 설명 :
2015-01-02 에는 전날보다 기온이 높아졌다. (10->25).
2015-01-04 에는 전날보다 기온이 높아졌다. (20->30).
풀이
-- DATE_ADD 사용 runtime 332ms
SELECT w1.id
FROM Weather w1
JOIN Weather w2
ON w1.recordDate = DATE_ADD(w2.recordDate, INTERVAL 1 DAY)
WHERE w1.temperature > w2.temperature
;
노트 (DATE_ADD 함수)
DATE_ADD 함수 :
날짜에 시간/날짜 간격을 추가한 다음 날짜를 반환
Syntax :
DATE_ADD(기준 날짜, INTERVAL 값 추가 단위)
예시 :
SELECT DATE_ADD("2017-06-15", INTERVAL 10 DAY); -- result : -- 2017-06-25
참고 : https://www.w3schools.com/mysql/func_mysql_date_add.asp
W3Schools.com
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
다른 풀이
-- DATEDIFF 사용 runtime 515 ms
SELECT w1.id
FROM Weather w1, Weather w2
WHERE DATEDIFF(w1.recordDate, w2.recordDate) = 1
AND w1.temperature > w2.temperature
;
노트 (DATEDIFF 함수)
DATEDIFF 함수 :
두 날짜 값 사이의 일수를 반환 (date1 - date2)
Syntax :
DATEDIFF(date1, date2)
예시 :
SELECT DATEDIFF("2017-01-01", "2016-12-24"); -- result : -- 8
참고 : https://www.w3schools.com/mysql/func_mysql_datediff.asp
W3Schools.com
W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.
www.w3schools.com
[LeetCode] SQL 50 - 197. Rising Temperature : https://leetcode.com/problems/rising-temperature/description/?envType=study-plan-v2&envId=top-sql-50
'문제 풀이 > LeetCode' 카테고리의 다른 글
[LeetCode] SQL 50 - 1934. Confirmation Rate (MySQL) (0) | 2024.08.07 |
---|---|
[LeetCode] SQL 50 - 570. Managers with at Least 5 Direct Reports (MySQL) (0) | 2024.08.06 |
[LeetCode] SQL 50 - 1280. Students and Examinations (MySQL) (0) | 2024.07.26 |
[LeetCode] SQL 50 - 1661. Average Time of Process per Machine (MySQL) (0) | 2024.07.26 |