Поправки, с учетом замечания
Cygapb-007:
declare @n int = 4;
declare @t table (a int identity(1,1) primary key, b int, c int check (c between 0 and 4));
insert into @t
(b, c)
values
(4, 0), (4, 1), (4, 2), (4, 3), (4, 4),
(1, 0), (1, 1), (1, 2), (1, 3),
(2, 0), (2, 1), (2, 2),
(3, 0), (3, 1), (3, 1), (3, 3), (3, 3);
with x as
(
select
*,
@n - (dense_rank() over (partition by b order by c) - 1) as r1,
dense_rank() over (partition by b order by c desc) - 1 as r2,
row_number() over (partition by b order by a, c) +
row_number() over (partition by b order by a desc, c desc) as n
from
@t
)
select
a, b, c
from
x
where
r1 <> r2 or n > @n + 2;