select OriginalDocumentNumber ,FilterRound , p2_Reason , p2_FinalGrade , rowno , s_index , t_index
from (
select * ,
rowno=row_number() over (partition by OriginalDocumentNumber,FilterRound order by p2_FinalGrade desc) ,
s_index = ROW_NUMBER() OVER(PARTITION BY FilterRound,OriginalDocumentNumber ORDER BY p2_FinalGrade),
t_index = DENSE_RANK() OVER (ORDER BY p2_FinalGrade)
from #TempDa
) l
where
l.p2_FinalGrade in ('d','f')
and l.rowno = 1
and l.OriginalDocumentNumber = '590200054'
and l.p2_Reason = 'ไกลเกินไป/กำลังซื้อน้อย'
and l.OriginalDocumentNumber+l.FilterRound not in (select OriginalDocumentNumber+FilterRound from #TempDa where p2_FinalGrade in ('a','b','c')
)