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.TIP as tip,
	b.sfrkomitent as sfr,
	CASE 
		WHEN b.tip = 'DAT_AVANS' THEN b.iznos
		WHEN b.tip = 'DAT_AVANS_POVRACAJ' THEN  -b.iznos 
		WHEN b.tip = 'ZATVARANJE_AVANSOM_DOBAVLJAC' THEN  -b.iznos 
		ELSE 0
		END as iznos,
	coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and (b.tip = 'DAT_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_DOBAVLJAC') ),0) as osnovica,
		coalesce((select sum(t.osnovica) from dtaksa t where b.iddok = t.iddok and (b.tip = 'DAT_AVANS' ) ),0) as osnovica1,
		
	coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and (b.tip = 'DAT_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_DOBAVLJAC') ),0) as pdv,
		coalesce((select sum(t.iznos) from dtaksa t where b.iddok = t.iddok and (b.tip = 'DAT_AVANS' ) ),0) as pdv1,

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

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

	o.str3


FROM 
	dokument b, opstidokument o 
WHERE 
	(b.tip = 'DAT_AVANS' OR b.tip = 'DAT_AVANS_POVRACAJ' or b.tip = 'ZATVARANJE_AVANSOM_DOBAVLJAC') and b.arhiviran = 1 and b.iddok = o.iddok 
	 
	)x 
	group by sfr, str3
	order by sfr
)Y WHERE IZN != 0 OR osn != 0 OR pdv != 0