CREATE OR REPLACE VIEW vw_bi_fct_open_position 
AS
    -- Sign physical contracted quantities
    SELECT 
        FTL."intTradeId",
        FTL."Trade Category",
        FTL."Delivery Date",    
        CASE
            WHEN FTL."Trade Type" = 'Purchase' THEN 1
            ELSE -1
            END * FTL."Quantity"  AS "Quantity"
    FROM vw_bi_fct_trade_line AS FTL
    UNION ALL
    -- Deduct delivered quantities
    SELECT 
        FFE."inTradeId",
        FFE."Trade Category",
        FFE."Event Date" AS "Delivery Date",
        CASE
            WHEN FFE."Trade Type" = 'Purchase' THEN -1
            ELSE 1
            END * SUM(FFE."Quantity") AS "Quantity"

    FROM vw_bi_fct_trade_fulfillment_event AS FFE
    WHERE FFE."Trade Category" = 'Physical'
    GROUP BY 
        FFE."inTradeId",
        FFE."Trade Category",
        FFE."Event Date",
        FFE."Trade Type";
        
ALTER TABLE public.vw_bi_fct_open_position
    OWNER TO postgres;      

    
