\encoding UTF8
COPY (SELECT query_to_xml('
SELECT pcst.tetel_kod as product_id, pcst.partner_csoport_kod as customer_group,
       pcst.egysegar as price, pcst.mennyiseg1 as quantity, pcstk.datum1 as date_start,
       pcstk.datum2+1 as date_end, pcst.kampany_kod as campaign, 0 as deleted
  FROM partner_csoport_tetel pcst
  LEFT JOIN partner_csoport_tetel_kampany pcstk ON pcst.kampany_kod = pcstk.kod
  LEFT JOIN tetel t ON t.kod = pcst.tetel_kod
  WHERE pcstk.datum1 <= current_date
    AND pcstk.datum2 >= current_date
    AND pcst.kod in
	(SELECT pcst_al.kod
	   FROM partner_csoport_tetel pcst_al
	   LEFT JOIN partner_csoport_tetel_kampany pcstk_al ON pcst_al.kampany_kod = pcstk_al.kod
	  WHERE pcstk_al.datum1 <= current_date
	    AND pcstk_al.datum2 >= current_date
	    AND pcst_al.tetel_kod = pcst.tetel_kod
	    AND pcst_al.partner_csoport_kod = pcst.partner_csoport_kod
	    AND ((pcst_al.mennyiseg1 = pcst.mennyiseg1) or (pcst_al.mennyiseg1 is null))
	  ORDER BY pcst.egysegar DESC
	  LIMIT 1)
    AND ( ((pcst.lasteditedtime_forsync + interval ''48 hours'') > current_timestamp) 
          OR ((pcstk.lasteditedtime_forsync + interval ''48 hours'') > current_timestamp)
          OR ((t.lasteditedtime_forsync + interval ''48 hours'') > current_timestamp) )
UNION
SELECT t.kod as product_id, pcs.kod as customer_group,
       te.egysegar as price, null as quantity, null as date_start,
       null as date_end, 0 as campaign, iif(not(t.akcios = 1), 1, 0) as deleted
  FROM tetel t
  LEFT JOIN tetel_egysegar te ON te.tetel_kod = t.kod AND te.egysegar_kod = (SELECT kod FROM egysegarak e WHERE e.deviza_nev = ''HUF'' AND e.alapertelmezett = 1)
  CROSS JOIN partner_csoport pcs
  WHERE (not(pcs.kod = 0))
    AND ( ((t.lasteditedtime_forsync + interval ''48 hours'') > current_timestamp) )
    AND (not((t.kod, pcs.kod) in (SELECT pcst.tetel_kod as product_id, pcst.partner_csoport_kod as customer_group
  FROM partner_csoport_tetel pcst
  LEFT JOIN partner_csoport_tetel_kampany pcstk ON pcst.kampany_kod = pcstk.kod
  WHERE pcstk.datum1 <= current_date
    AND pcstk.datum2 >= current_date
    AND pcst.kod in
	(SELECT pcst_al.kod
	   FROM partner_csoport_tetel pcst_al
	   LEFT JOIN partner_csoport_tetel_kampany pcstk_al ON pcst_al.kampany_kod = pcstk_al.kod
	  WHERE pcstk_al.datum1 <= current_date
	    AND pcstk_al.datum2 >= current_date
	    AND pcst_al.tetel_kod = pcst.tetel_kod
	    AND pcst_al.partner_csoport_kod = pcst.partner_csoport_kod
	    AND ((pcst_al.mennyiseg1 = pcst.mennyiseg1) or (pcst_al.mennyiseg1 is null))
	  ORDER BY pcst.egysegar DESC
	  LIMIT 1)
) ) )



ORDER BY 1,2', true, false, '')) to '/tmp/flexovit_tetel-kedvezmeny_changed.xml'