开始使用免费开始使用

使用 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;
编辑并运行代码