I need to find so called first entry in database for items regarding their partners.
I wrote query and it is giving me correct results but it sucks with performances.
I suspect that I have missed conception therefore this query can be written much better.
So I am asking you to help me redesign this query to get better performance.
My running database system is Sql Server 2008
declare @od_datuma datetime
declare @do_datuma datetime
set @od_datuma='2011-12-01'
set @do_datuma='2011-12-31'
select
doc.PAR_ID
,sdo.art_id
,MIN(doc.id) as doc_id
from
dokumenti
inner join DOC on dokumenti.tip=DOC.TIP
inner join SDO on DOC.ID=SDO.DOC_ID
left outer join (
select par_id,art_id from dokumenti
inner join DOC on dokumenti.tip=DOC.TIP
inner join SDO on DOC.ID=SDO.DOC_ID
where dokumenti.NABAVA =1 and
dokumenti.KOL_UL=1 and
DOC.DATUM<@od_datuma
) as stari_uazi on DOC.PAR_ID=stari_uazi.PAR_ID and SDO.ART_ID=stari_uazi.ART_ID
where
dokumenti.NABAVA =1 and
dokumenti.KOL_UL=1 and
stari_uazi.ART_ID is null and
doc.datum between @od_datuma and @do_datuma
group by doc.PAR_ID,sdo.art_id