CREATE OR REPLACE VIEW public.vw_fx_by_maturity_sum AS
 SELECT period,
    max(maturity_date) AS max,
    max(amount_remaining_contract) AS rem_ct,
    COALESCE(max(amount_remaining_forex), (0)::numeric) AS rem_fx,
    (COALESCE(max(amount_remaining_contract), (0)::double precision) - COALESCE((max(amount_remaining_forex))::double precision, (0)::double precision)) AS req_fx
   FROM ( SELECT vw_fx_by_maturity_by_contract.maturity_month AS period,
            max(vw_fx_by_maturity_by_contract.maturity_date) AS maturity_date,
            sum(vw_fx_by_maturity_by_contract.amount_remaining) AS amount_remaining_contract,
            NULL::numeric AS amount_remaining_forex
           FROM vw_fx_by_maturity_by_contract
          GROUP BY vw_fx_by_maturity_by_contract.maturity_month
        UNION ALL
         SELECT vw_fx_by_maturity_by_forex.maturity_period AS period,
            max(vw_fx_by_maturity_by_forex.maturity_date) AS maturity_date,
            NULL::double precision AS amount_remaining_contract,
            sum(vw_fx_by_maturity_by_forex.amount_remaining) AS amount_remaining_forex
           FROM vw_fx_by_maturity_by_forex
          GROUP BY vw_fx_by_maturity_by_forex.maturity_period) m
  GROUP BY period;;
