declare @startID int, @endID int, @rowsEach int
select @startID = 0, @endID = 2, @rowsEach = 3
select *
from
(
select memID, foo, bar, foobar, row_number() over (partition by dense_rank order by dense_rank) [rank_row]
from
(
select memID, foo, bar, foobar, dense_rank() over (order by memID) [dense_rank]
from #test
where memID between @startID and @endID
) a
) b
where rank_row <= @rowsEach
Результат:
memID foo bar foobar rank_row
----------- ---- ---- ------ --------------------
1 blah blah blah 1
1 blah blah blah 2
1 blah blah blah 3
2 blah blah blah 1
2 blah blah blah 2
2 blah blah blah 3
А вот код настройки, если вы хотите выполнить локальное тестирование:
create table #test
(
memID int not null
, foo char(4) not null
, bar char(4) not null
, foobar char(4) not null
)
insert into #test (memID, foo, bar, foobar)
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 1, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 2, 'blah', 'blah', 'blah'
union all
select 10001, 'blah', 'blah', 'blah'
union all
select 10001, 'blah', 'blah', 'blah'
union all
select 10001, 'blah', 'blah', 'blah'