-- completare ips_regdoc cu nave lipsa din istorice cu mai multe declaratii

merge into ips_regdoc a using
(select bdv.* from
(Select v.numar_act, v.data_act as data, 1 as tip, v.id_part as id_client, v.id_ctr as id_contract, v.curs, v.id_vanzare, vv.declaratio as document, b.id_locatia, bd.id_articol, bd.id_valuta, 1 as cantitate, Sum(bd.valftva) As valftva, Sum(bd.valtva) As valtva, Sum(bd.valctva) As valctva, Sum(bd.valval) As valval, Sum(bd.valval) As Pret 
	From ips_berthing_details_vanzari bd Join ips_berthings_vanzari b On bd.bv_id = b.Id 
  join ips_vvoyages_vanzari vv on b.vv_id = vv.vv_id
  join vanzari v on vv.vz_id = v.id_vanzare
	where extract(year from v.data_act) = 2020 and v.tip_factura = 1
	Group By v.numar_act, v.data_act, v.id_part, v.id_ctr, v.curs, v.id_vanzare, vv.declaratio, b.id_locatia, bd.id_articol, bd.id_valuta) bdv left join 
  ips_regdoc r on bdv.document = r.document and bdv.id_vanzare = r.id_vanzare and bdv.id_locatia = r.id_locatia and bdv.id_articol = r.id_articol and bdv.id_valuta = r.id_Valuta
  where bdv.valftva <> nvl(r.valftva,0)) b on (a.id_vanzare = b.id_vanzare and a.document = b.document and a.id_locatia = b.id_locatia and a.id_articol = b.id_articol and a.id_Valuta = b.id_valuta)
  when not matched then
    insert (id_vanzare, tip, document, data, id_client, id_contract, id_locatia, id_articol, valftva, valtva, valctva, valval, Pret, curs, id_valuta, cantitate)
    values (b.id_vanzare, b.tip, b.document, b.data, b.id_client, b.id_contract, b.id_locatia, b.id_articol, b.valftva, b.valtva, b.valctva, b.valval, b.valval, b.curs, b.id_valuta, b.cantitate);