I'm a bit confused how you expect anyone to be able to help you write a query like this when you don't provide ddl and sample data to explain how the tables are structured and what kind of data this is. Not to mention you don't provide an example of an expected rowset.As best I can tell, you are looking for a top n records within groupings. I hope this example helps you.create table #temp ( JobID int, Step varchar(10))set nocount oninsert #temp values (1,'a')insert #temp values (1,'b')insert #temp values (1,'c')insert #temp values (1,'d')insert #temp values (1,'e')insert #temp values (1,'f')insert #temp values (1,'g')insert #temp values (1,'h')insert #temp values (1,'i')insert #temp values (2,'a')insert #temp values (2,'b')insert #temp values (2,'c')insert #temp values (2,'d')insert #temp values (2,'e')insert #temp values (2,'f')insert #temp values (2,'g')insert #temp values (2,'h')insert #temp values (2,'i')goselect JobId, Stepfrom #temp twhere exists ( select 1 from #temp where jobid = t.jobid and step = t.step group by jobid having (select count(*) from #temp where jobid = t.jobid and step < t.step ) < 3 )go
This example will return the top 3 'Steps' for each 'JobID' in #temp.<O>