LAG로 기간 비교하기
Idaho 지역 사무소에서는 선택된 각 검사 기간(연도와 월)마다 수행된 검사 건수를 확인하고, 바로 이전 기간과 비교하고자 합니다. 먼저 Minidoka 카운티의 검사 지점 13903부터 시작해 보세요.
이 연습은 강의의 일부입니다
Redshift 입문
연습 안내
- CTE
minidoka_13903를 만들고,idaho_sample에서 모든 열을 선택하되, 지점 13903에 대해sample_date를 날짜로 변환한 추가 열(date_sampled)을 포함하세요. - 메인 쿼리에서:
- 현재 월의 레코드 수를 계산하세요.
- 윈도 함수로 이전 월의 레코드 수를 계산하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
WITH minidoka_13903 AS (
SELECT *,
-- Converts the sample_date to a date
___(___ AS ___) as date_sampled
FROM public_intro_redshift.idaho_samples
WHERE fk_monitoringlocation = 13903
)
SELECT DATE_PART('year', date_sampled) as sample_year,
DATE_PART('month', date_sampled) as sample_month,
-- Count the records
___,
-- Count the records for the prior month
___(___, ___) OVER (
ORDER BY DATE_PART('year', date_sampled),
DATE_PART('month', date_sampled)
) AS prior_readings
-- Use the prefiltered CTE you created above
FROM ___
GROUP BY sample_year,
sample_month
ORDER BY sample_year DESC,
sample_month DESC;