create or replace function f_get_rqa_plpd(plpdId number, deliveryDate date, firstDelivery number)
  return number is
  res            number;
  v_plpdId       number := plpdId;
  v_deliveryDate date := deliveryDate;
  v_firstDelivery number := firstDelivery;
begin
  if (v_firstDelivery = 0) then
    select nvl(sum(RQA.QUANTITY), 0) into res
            from RENTALQTYADJUSTMENT RQA
            left outer join DELIVERYVARIATIONS DV
              on RQA.DELIVERYVARIATIONS_ID = DV.DELIVERYVARIATIONS_ID
           where RQA.PRODUCTLISTPERDISTRIBPOINT_ID = v_plpdId
             and RQA.ADJUSTMENTDATE <= v_deliveryDate;
  end if;
  if (v_firstDelivery = 1) then
    select nvl(sum(RQA.QUANTITYFIRSTDELIVERY), 0) into res
            from RENTALQTYADJUSTMENT RQA
           where RQA.PRODUCTLISTPERDISTRIBPOINT_ID = v_plpdId
             and RQA.ADJUSTMENTDATE <= v_deliveryDate;
  end if;
  
  return res;
end f_get_rqa_plpd;
/
