WITH
l_o AS (
SELECT
MAX(entry_date) AS entry_date,
country_icao_code,
country_name,
SUM(flt_o) / 7 AS flt_o_avg
FROM
daio
WHERE
${latest_minus_seven_date} < entry_date AND entry_date <= ${latest_date}
GROUP BY
country_icao_code, country_name),
r_o AS (
SELECT
MAX(entry_date) as entry_date,
country_icao_code,
country_name,
SUM(flt_o) / 7 AS flt_o_avg
FROM
daio
WHERE
${reference_minus_seven_date} < entry_date AND entry_date <= ${reference_date}
GROUP BY
country_icao_code, country_name)
SELECT
f1.entry_date AS latest_date,
f0.entry_date AS reference_date,
f1.country_icao_code AS id,
f1.country_name AS state,
f1.flt_o_avg AS flt_o_avg_latest,
f0.flt_o_avg AS flt_o_avg_preC19,
(f1.flt_o_avg - f0.flt_o_avg) AS delta,
ROUND(100 *(f1.flt_o_avg - f0.flt_o_avg) / f0.flt_o_avg) AS variation
FROM
l_o f1, r_o f0
WHERE
f0.country_icao_code = f1.country_icao_code