SELECT 
	0 as iddok,
	'POCETNO' as ozndokumenta,
	'RACUN_DOBAVLJACA' as tip,
	'POCETNO' as podtip,
	'2013-01-01' as datum,
	'2013-01-01' as datarh,
	'2013-01-01' as datvalute,
	'2013-01-01' as datprometa,
	1 as arhiviran,
	1 as proknjizen,
	0 as kepu,
	0 as rbroj,
	-1 as rbrdok,
	0 as rbrkepu,
	'Grupno pocetno stanje' as opis,
	0 as storno,
	sum(f.iznos) as iznos,
	sum(f.stornoiznos) as stornoiznos,
	sum(f.uplata) as uplata,
	sum(f.zaduzenje) as zaduzenje,
	sum(f.razduzenje) as razduzenje,
	'p' as usernamepoc,
	'p' as usernamekraj,
	null as oznogranak,
	null as oznrj,
	d.sfrkomitent,
	null as original,
	'U' as vrsta,
	1 as cvprodajna,
	sum(f.vrednostrobe) as vrednostrobe,
	sum(f.vrednostusluga) as vrednostusluga,
	0 as iddok,
	'POCETNO' as ozndokumenta,
	'RACUN_DOBAVLJACA' as tip,
	'POCETNO' as podtip,
	'2013-01-01' as datum,
	'2013-01-01' as datfakture,
	'2013-01-01' as datdpo,
	'2013-01-01' as datarh,
	'2013-01-01' as datvalute,
	sum(d.iznos) as iznos,
	0 as procrabata,
	1 as arhiviran,
	1 as proknjizen,
	0 as storno,
	'' as tipkalkulacije,
	sum(d.trosakbezpdv) as trosakbezpdv,
        0 as kurs,
	d.sfrkomitent as sfrkomitent,
	null as oznrj,
	null as oznogranak,
	'p' as usernamepoc,
	'p' as usernamekraj,
	null as original,
	'0' as rbroj,
	-1 as rbrdok,
	'' as pdv,
	'' as poruka,
	sum(d.uplata) as uplata,
	sum(d.prodvrednost) as prodvrednost,
	sum(d.cvprodajna) as cvprodajna,
	sum(d.stornoiznos) as stornoiznos,
	sum(d.ukupnofakturisano) as ukupnofakturisano,
	sum(d.troskoviinterni) as troskoviinterni,
	sum(d.troskovieksterni) as troskovieksterni,
	sum(d.troskovicarina) as troskovicarina,
	sum(d.vrednostrobe) as vrednostrobe,
	sum(d.nabavnavrednost) as nabavnavrednost, 
	sum(d.zaokruzenje) as zaokruzenje,
	'RACUN_DOBAVLJACA' as discriminator,
	sum(d.osnovica) as osnovica,
	sum(d.bezprava) as bezprava,
	sum(d.oslobodjeno) as oslobodjeno,
	null as idkalkulacija
FROM 
	dokument f, kalkulacija d
WHERE 
	f.arhiviran=1 AND f.storno= 0 AND f.iznos - f.stornoIznos - f.uplata <> 0 AND 
	((f.tip='KALKULACIJA' AND 
	(f.podtip='FAKTURA' OR f.podtip='POCETNO')) OR 
	(f.tip='TROSAK' AND f.podtip = 'EKSTERNI') OR 
	f.tip='RACUN_DOBAVLJACA' OR 
	f.tip='ZAPISNIK_OTPREMNICE')
	and f.iddok = d.iddok 
group by
d.sfrkomitent
order by 
d.sfrkomitent