Periodes vergelijken met lag
Het field office in Idaho wil zien hoeveel tests er in elke testperiode (jaar en maand) zijn uitgevoerd waarin het is geselecteerd, en dit vergelijken met de voorgaande periode. Ze willen beginnen met testlocatie 13903 in Minidoka County.
Deze oefening maakt deel uit van de cursus
Introductie tot Redshift
Oefeninstructies
- Bouw een CTE,
minidoka_13903, die alle kolommen uitidaho_sampleselecteert ensample_dateomzet naar een datum als extra kolom (date_sampled) voor station 13903. - In de hoofdquery:
- Tel de records voor de huidige maand
- Tel de records voor de vorige maand via een windowfunctie.
Praktische interactieve oefening
Probeer deze oefening eens door deze voorbeeldcode in te vullen.
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;