Hi Experts,
I have table called ABC, having i million records. when I Run below query it is taking around 7 mins. Can anybody help me to optimize the query.
DECLARE @FINAL_RESULT TABLE
(
BTI1 nvarchar(50) ,
CLASS1 nvarchar(10)
)
insert into @FINAL_RESULT (BTI1,CLASS1)
select b1.BTI,c.CLASS from
(
select b.CLASS,b.DAT,b.REF,b.BTI,b.COL1,b.COL2,b.COL3
FROM (
SELECT REF,Max(BTI) as BTI
from ABC
group by REF
) a
left join ABC b on a.BTI=b.BTI
where CLASS in ('TEST', 'TEST1','TEST2')
)c
right join ABC b1 on (c.COL1=b1.COL1 and c.COL2=b1.COL2 and c.COL3=b1.COL3)
where c.REF <> b1.REF
and datediff(dd,b1.DAT,c.DAT) <= 20
update ABC set FINAL_COL = CLASS1
from ABC,@FINAL_RESULT
where ABC.BTI =BTI1