การเปรียบเทียบช่วงเวลาด้วย lag
สำนักงานภาคสนาม Idaho ต้องการดูจำนวนการทดสอบที่ดำเนินการในแต่ละช่วงเวลา (ปีและเดือน) ที่ถูกเลือก และเปรียบเทียบกับช่วงเวลาก่อนหน้า โดยจะเริ่มต้นที่สถานีทดสอบ 13903 ในเขต Minidoka
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Introduction to Redshift
คำแนะนำการฝึกหัด
- สร้าง CTE ชื่อ
minidoka_13903โดย SELECT คอลัมน์ทั้งหมดจากidaho_sampleและแปลงsample_dateให้เป็น date เป็นคอลัมน์เพิ่มเติม (date_sampled) สำหรับสถานี 13903 - ใน main query:
- นับจำนวนเรคคอร์ดของเดือนปัจจุบัน
- นับจำนวนเรคคอร์ดของเดือนก่อนหน้าผ่าน window function
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
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;