Programming/SQL
[leetcode | SELECT, EXISTS] Rising Temperature
용스토리랜드
2024. 8. 14. 18:57
💡문제 설명
💡정답 코드 (SUBQUERY, EXISTS)
# 전날에 비해 온도가 높아진 날의 id 를 추출
SELECT current_day.id
FROM Weather AS current_day
WHERE EXISTS(
SELECT 1
FROM Weather AS yesterday
WHERE current_day.temperature > yesterday.temperature
AND current_day.recordDate = yesterday.recordDate + INTERVAL 1 DAY
* EXISTS
- EXISTS 는 SQL 에서 사용되는 논리 연산자
- 특정 조건을 만족하는 서브쿼리가 존재하는지를 확인
- EXISTS 뒤에 오는 서브쿼리가 하나 이상의 결과를 반환하면 TRUE 로 평가되고, 그렇지 않으면 FALSE 로 평가
SELECT 1
FROM Weather AS yesterday
WHERE current_day.temperature > yesterday.temperature
AND current_day.recordDate = yesterday.recordDate + INTERVAL 1 DAY
- 서브쿼리 내에서 두 가지 조건을 검사
- 1. 기온 비교
- 'current_day.temperature > yesterday.temperature'
- current_day 의 각 행을 순서대로 훑어 내려가며 yesterday 테이블의 temperature 와 모두 비교하여 true 인 값을 찾는다.
- 현재 날짜의 기온이 전날의 기온보다 높은지 확인
- 2. 날짜 비교
- current_day.recordDate = yesterday.recordDate + INTERVAL 1 DAY
- current_day 테이블의 recordDate 가 yesterday 테이블의 recordDate 보다 하루 앞섰을 때만을 조건으로 한다.
- Exists 를 통해 두가지 조건을 모두 만족한다면, current_day 테이블에서 하루 앞서면서, 기온도 높은 행들에 대하여 True 값들을, 아니면 False 값들을 반환하게 된다.
- 1. 기온 비교
- INTERVAL 1 DAY
- INTERVAL 은 SQL 에서 날짜나 시간을 조작할 때 사용하는 키워드
- INTERVAL 1 DAY 는 특정 날짜에 1일을 더한다.
- SELECT 1 의 역할 ?
- 서브쿼리를 만족하는 행이 1개 이상있다는 것을 의미
💡정답 코드 (JOIN)
select w1.id
from weather w1
join weather w2
on DATEDIFF(w1.recordDate, w2.recordDate) = 1
where w1.temperature > w2.temperature;
💡정답 코드 (CTE)
with PreviousWeatherData as
(
select
id,
recordDate,
temperature,
LAG(temperature, 1) over (order by recordDate) as PreviousTemperature,
LAG(recordDate, 1) over (order by recordDate) as PreviousRecordDate
from
basic.Weather
)
select id
from PreviousWeatherData
where temperature > PreviousTemperature
and recordDate = DATE_ADD(PreviousRecordDate, interval 1 day);
*LAG(column1, n) OVER(ORDER BY column2) as column_name
n 번째 이전의 column1 값을 가져와서(column2 를 기준으로 정렬하고, column_name 으로 명명하기) 새로운 행으로 할당
반응형