เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การเปรียบเทียบช่วงเวลาด้วย 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;
แก้ไขและรันโค้ด