CREATE OR REPLACE VIEW public.vw_bi_itsa_fct_contract AS WITH valuation_info AS ( SELECT pvl."intContractId", pvl."intContractLineId", pvl."strState", avg(pvl."dblPrice") AS "avgPrice", avg(pvl."dblMtmPrice") AS "avgMtmPrice" FROM vw_utility_physical_valuation_line pvl GROUP BY pvl."intContractId", pvl."intContractLineId", pvl."strState" ) SELECT 'Purchase'::text AS "TradeType", pc."intPurchaseLineId" AS "TradeLineId", pc."dblQuantity" AS "Quantity", pc."dblTheoriticalQuantity" AS "Contract Quantity", pc."dblInInstructedQuantity" AS "InstructedQuantity", CASE WHEN (pc."ysnFinished" = true) THEN (0)::numeric(18,3) WHEN ((pc."dblTheoriticalQuantity")::double precision > pc."dblInInstructedQuantity") THEN (((pc."dblTheoriticalQuantity")::double precision - pc."dblInInstructedQuantity"))::numeric(18,3) ELSE (0)::numeric(18,3) END AS "Open Quantity", COALESCE(pc."dtmEstimatedBLDate", pc."dtmDeliveryDateFrom") AS "Delivery Date", COALESCE(vi."strState", 'Unknown'::text) AS "Price Fixing Status", COALESCE(vi."avgPrice", (0)::numeric) AS "Avg Price", COALESCE(vi."avgMtmPrice", (0)::numeric) AS "Avg Mtm Price", pc."dblTheoriticalQuantity" AS "Contract Quantity Signed", pc."dblInInstructedQuantity" AS "Instructed Quantity Signed" FROM (vw_utility_purchase_physical_contract pc LEFT JOIN valuation_info vi ON ((pc."intPurchaseLineId" = vi."intContractLineId"))) WHERE (1 = 1) UNION ALL SELECT 'Sale'::text AS "TradeType", pc."intSaleLineId" AS "TradeLineId", pc."dblQuantity" AS "Quantity", pc."dblTheoreticalQuantity" AS "Contract Quantity", pc."dblInstructedQuantity" AS "InstructedQuantity", CASE WHEN (pc."ysnFinished" = true) THEN (0)::numeric(18,3) WHEN ((pc."dblTheoreticalQuantity")::double precision > pc."dblInstructedQuantity") THEN (((pc."dblTheoreticalQuantity")::double precision - pc."dblInstructedQuantity"))::numeric(18,3) ELSE (0)::numeric(18,3) END AS "Open Quantity", COALESCE(pc."dtmEstimatedBLDate", pc."dtmDeliveryDateFrom") AS "Delivery Date", COALESCE(vi."strState", 'Unknown'::text) AS "Price Fixing Status", COALESCE(vi."avgPrice", (0)::numeric) AS "Avg Price", COALESCE(vi."avgMtmPrice", (0)::numeric) AS "Avg Mtm Price", (pc."dblTheoreticalQuantity" * ('-1'::integer)::numeric) AS "Contract Quantity Signed", (pc."dblInstructedQuantity" * (('-1'::integer)::numeric)::double precision) AS "Instructed Quantity Signed" FROM (vw_utility_sale_physical_contract pc LEFT JOIN valuation_info vi ON ((pc."intSaleLineId" = vi."intContractLineId"))) WHERE (1 = 1);;