CREATE OR REPLACE VIEW public.vw_bi_itsa_fct_inherited_expenses_on_shipments AS
 WITH all_fees AS (
         SELECT 3 AS "intPnlTypeId",
            ((shipment."intPurchaseLineId" || '_'::text) || shipment."intSaleLineId") AS "strConformedReferenceId",
            2 AS "intPriceGroupId",
            ctr_fees."Fee" AS "Line Description",
            (shipment."Shipped Quantity")::double precision AS "Open Quantity Signed",
            ctr_fees."Price",
            ((shipment."Shipped Quantity")::double precision * (ctr_fees."Price")::double precision) AS "Amount",
            shipment."BL Date" AS "Delivery Date",
            ctr_fees."Cost Group" AS "Line Group",
            shipment."intBookId"
           FROM (vw_bi_itsa_fct_shipments_v2 shipment
             JOIN vw_bi_itsa_fct_contract_fees ctr_fees ON ((ctr_fees."intContractLineId" = shipment."intPurchaseLineId")))
        UNION ALL
         SELECT 3 AS "intPnlTypeId",
            ((shipment."intPurchaseLineId" || '_'::text) || shipment."intSaleLineId") AS "strConformedReferenceId",
            2 AS "intPriceGroupId",
            fees."Fee" AS "Line Description",
            (shipment."Shipped Quantity")::double precision AS "Open Quantity Signed",
            fees."Price",
            ((shipment."Shipped Quantity")::double precision * (fees."Price")::double precision) AS "Amount",
            shipment."BL Date" AS "Delivery Date",
            fees."Cost Group" AS "Line Group",
            shipment."intBookId"
           FROM (vw_bi_itsa_fct_shipment_fees fees
             JOIN vw_bi_itsa_fct_shipments_v2 shipment ON ((fees."intShipmentId" = shipment."intShipmentId")))
        )
 SELECT all_fees."intPnlTypeId",
    all_fees."strConformedReferenceId",
    all_fees."intPriceGroupId",
    all_fees."Line Description",
    all_fees."Open Quantity Signed",
    all_fees."Price",
    all_fees."Amount",
    all_fees."Delivery Date",
    all_fees."Line Group",
    all_fees."intBookId"
   FROM all_fees
  WHERE ((all_fees."Line Description")::text <> 'Profit sharing'::text)
UNION ALL
 SELECT ranked."intPnlTypeId",
    ranked."strConformedReferenceId",
    ranked."intPriceGroupId",
    ranked."Line Description",
    ranked."Open Quantity Signed",
    ranked."Price",
    ranked."Amount",
    ranked."Delivery Date",
    ranked."Line Group",
    ranked."intBookId"
   FROM ( SELECT all_fees."intPnlTypeId",
            all_fees."strConformedReferenceId",
            all_fees."intPriceGroupId",
            all_fees."Line Description",
            all_fees."Open Quantity Signed",
            all_fees."Price",
            all_fees."Amount",
            all_fees."Delivery Date",
            all_fees."Line Group",
            all_fees."intBookId",
            row_number() OVER (PARTITION BY all_fees."strConformedReferenceId" ORDER BY all_fees."Price" DESC) AS rn
           FROM all_fees
          WHERE ((all_fees."Line Description")::text = 'Profit sharing'::text)) ranked
  WHERE (ranked.rn = 1);;
