使用 LAG 比較不同期間
Idaho 的外勤辦公室想查看在每個被選取的檢測期間(年與月)進行了多少次檢測,並與前一個期間比較。他們想先從 Minidoka 縣的檢測站 13903 開始。
本練習屬於課程
Redshift 入門
練習說明
- 建立一個 CTE,
minidoka_13903,從idaho_sample選取所有欄位,並將sample_date轉成日期作為額外欄位(date_sampled),篩選站台 13903。 - 在主查詢中:
- 計算當月的筆數。
- 透過視窗函式計算上個月的筆數。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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;