CREATE PROCEDURE "DBA"."pr_koond1_saldoandmik_sa"()
BEGIN
  delete from gl_pr_saldoandmik;
  insert into gl_pr_saldoandmik( konto,part,osa,allik,ravo,deebet,kreedit)
    select Left(gl_dk_koond.konto,6) as ab_konto,if gl_dk_koond.partnr = 0 then '' else Left(partlist.part,6) endif as ab_part,if gl_dk_koond.talnr = 0 then '' else if tallist.askood is null or Trim(tallist.askood)='' then "Left"(tallist.osa,5) else "Left"(tallist.askood,5) endif endif as ab_osa,if gl_dk_koond.alliknr = 0 then '' else "Left"(alliklist.allik,2) endif as ab_allik,if gl_dk_koond.ravonr = 0 then '' else "Left"(ravolist.ravo,2) endif as ab_ravo, sum(gl_dk_koond.adeeb-gl_dk_koond.akree+gl_dk_koond.deeb-gl_dk_koond.kree), sum(gl_dk_koond.akree-gl_dk_koond.adeeb+gl_dk_koond.kree-gl_dk_koond.deeb)
    from gl_dk_koond left outer join partlist on gl_dk_koond.partnr = partlist.partnr left outer join tallist on gl_dk_koond.talnr = tallist.talnr left outer join alliklist on gl_dk_koond.alliknr = alliklist.alliknr left outer join ravolist on gl_dk_koond.ravonr = ravolist.ravonr
    group by ab_konto,ab_part,ab_osa,ab_allik,ab_ravo;
  update gl_pr_saldoandmik set deebet = 0 where gl_pr_saldoandmik.deebet < 0;
  update gl_pr_saldoandmik set kreedit = 0 where gl_pr_saldoandmik.kreedit < 0;
  delete from gl_pr_saldoandmik where deebet = 0 and kreedit = 0;
  update gl_pr_saldoandmik left outer join kontlist on "Left"(gl_pr_saldoandmik.konto+'       ',7) = "Left"(kontlist.konto+'       ',7) left outer join pr_bil on kontlist.bilnr = pr_bil.bilnr set gl_pr_saldoandmik.deebet = -1*gl_pr_saldoandmik.kreedit,gl_pr_saldoandmik.kreedit = 0 where gl_pr_saldoandmik.kreedit > 0 and pr_bil.aktpas = 'A';
  update gl_pr_saldoandmik left outer join kontlist on "Left"(gl_pr_saldoandmik.konto+'       ',7) = "Left"(kontlist.konto+'       ',7) left outer join pr_bil on kontlist.bilnr2 = pr_bil.bilnr set gl_pr_saldoandmik.kreedit = -1*gl_pr_saldoandmik.deebet,gl_pr_saldoandmik.deebet = 0 where gl_pr_saldoandmik.deebet > 0 and pr_bil.aktpas = 'P'
END