i have a table which contains id , primaryid , data ,dataname columns i want only rows for which contains max id and primaryid
create table #temp
(
id int,
primaryid int,
data nvarchar(20),
data_name nvarchar(30)
)
insert into #temp
values (1,1,'3223sfd','434'),(1,2,'sdfsd','dfsdfsd'),
(1,3,'sdfs897d','898'),(1,4,'898','545'),(1,5,'898','uuyu'),
(2,1,'3223sfd','434'),(2,2,'sdfsd','dfsdfsd'),
(2,3,'sdfs897d','898'),(2,4,'898','545'),(2,5,'898','uuyu')
i achieve this with below query
select T.id , T.primaryid , T.data , T.data_name from #temp T , (select ID, max(primaryid) rank from #temp t2 group by id ) as T2
where t.primaryid = t2.rank group by T.id , T.primaryid , T.data , T.data_name
but my table have more than 100k records i want to worry about that
What will be optimized query for this?