Run the example below and you will see what I meant:CREATE TABLE #tmp(skid INT,c1 INT , c2 INT, c3 INT, c4 INT);INSERT INTO #tmp VALUES(1,1,1,1,10),(NULL,2,1,1,10),(NULL,3,1,1,11),(1,4,1,1,NULL),(NULL,5,1,1,NULL);select c1,row_number() over(partition by c2 order by c3 desc) as selectcol2from #tmp a1where exists(select 1 from #tmp a2 where skid is null and a1.c4=a2.c4)select c1,row_number() over(partition by c2 order by c3 desc) as selectcol2from #tmp where skid is nullDROP TABLE #tmp;