CREATE OR REPLACE VIEW food600.skontrolamigracie
 AS
 SELECT aaa.id_kas,
    aaa.uzaverka,
    aaa.cena_celk::numeric(10,2) AS cena_celk,
    aaa.cena_slev::numeric(10,2) AS cena_slev,
    (pol.prachy + fin.round50)::numeric(10,2) AS prachy,
    pol.prachy_puv::numeric(10,2) AS prachy_puv,
    plt.cena_pl::numeric(10,2) AS cena_pl,
    pol.c_uzaverka
   FROM ( SELECT sk_fin.id_kas,
            sk_fin.uzaverka,
            sum(sk_fin.cena_celk) AS cena_celk,
            sum(sk_fin.cena_slev + sk_fin.round50) AS cena_slev
           FROM food600.sk_fin
          GROUP BY sk_fin.uzaverka, sk_fin.id_kas) aaa
     LEFT JOIN ( SELECT sum(sk__pol.prachy) AS prachy,
            sum(sk__pol.prachy_puv) AS prachy_puv,
            sk__pol.c_uzaverka,
            sk__uza.uzaverka,
            sk__uza.id_kas
           FROM food600.sk__pol
             JOIN food600.sk__uza ON sk__uza.idriadok = sk__pol.c_uzaverka
          WHERE btrim(sk__pol.k_odpoctu::text) <> ''::text
          GROUP BY sk__pol.c_uzaverka, sk__uza.uzaverka, sk__uza.id_kas) pol ON aaa.uzaverka = pol.uzaverka AND aaa.id_kas = pol.id_kas
     LEFT JOIN ( SELECT sk__fin.c_uzaverka,
            sum(sk__fin.round50) AS round50
           FROM food600.sk__fin
          GROUP BY sk__fin.c_uzaverka) fin ON pol.c_uzaverka = fin.c_uzaverka
     LEFT JOIN ( SELECT sk__plt.c_uzaverka,
            sum(sk__plt.cena_pl) AS cena_pl
           FROM food600.sk__plt
          GROUP BY sk__plt.c_uzaverka) plt ON pol.c_uzaverka = plt.c_uzaverka
  WHERE length(btrim(aaa.uzaverka::text)) = 17
  ORDER BY aaa.uzaverka DESC, aaa.id_kas;
