SELECT * FROM
(SELECT 
	sfr, 
	sum(iznos) AS IZN , 
	sum(osnovica1)-sum(osnovica) AS OSN , 
	sum(pdv1)-sum(pdv) AS PDV, 
	sum(osnt12)-sum(osnt11),
	sum(pdvt12) - sum(pdvt11), 
	sum(osnt22)- sum(osnt21), 
	sum(pdvt22)-sum(pdvt21),
	str3  
FROM
(SELECT  
	b.sfrkomitent as sfr,
	CASE 
		WHEN b.tip = 'PRIMLJEN_AVANS' THEN b.iznos 
		WHEN b.tip = 'PRIMLJEN_AVANS_POVRACAJ' THEN  -b.iznos 
		WHEN b.tip = 'ZATVARANJE_AVANSOM_KUPAC' THEN  -b.iznos 
		ELSE 0
		END as iznos,
	coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and (b.tip = 'PRIMLJEN_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_KUPAC') ),0) as osnovica,
		coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and (b.tip = 'PRIMLJEN_AVANS' ) ),0) as osnovica1,
		
	coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and (b.tip = 'PRIMLJEN_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_KUPAC') ),0) as pdv,
		coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and (b.tip = 'PRIMLJEN_AVANS' ) ),0) as pdv1,

	coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T1' and (b.tip = 'PRIMLJEN_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_KUPAC') ),0) as osnt11,
		coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T1'  and (b.tip = 'PRIMLJEN_AVANS' ) ),0) as osnt12,

	coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T1' AND (b.tip = 'PRIMLJEN_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_KUPAC') ),0) pdvt11,
		coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T1' and (b.tip = 'PRIMLJEN_AVANS' ) ),0) as pdvt12,
		
	coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T2' and (b.tip = 'PRIMLJEN_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_KUPAC') ),0) as osnt21,
		coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T2'  and (b.tip = 'PRIMLJEN_AVANS' ) ),0) as osnt22,
	
	coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T2'  and (b.tip = 'PRIMLJEN_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_KUPAC') ),0) as pdvt21,
		coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and t.ozntargr = 'T2' and (b.tip = 'PRIMLJEN_AVANS' ) ),0) as pdvt22,

	o.str3

FROM 
	dokument b , opstidokument o 
WHERE 
	(b.tip = 'PRIMLJEN_AVANS' OR b.tip = 'PRIMLJEN_AVANS_POVRACAJ' OR b.tip = 'ZATVARANJE_AVANSOM_KUPAC') and b.arhiviran = 1 AND b.iddok = o.iddok 
	 
	)x WHERE x.iznos != 0.00
	group by sfr, str3
)Y WHERE IZN != 0 or osn != 0 or pdv != 0