获取结果集中结束位置的T-SQL查询

获取结果集中结束位置的T-SQL查询,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一个结果集,我将为它提供一个输入位置和一个用于迭代的数字。我期望最终的结果 ------------- ID ------------- 1 2 3 4 5 6 7 -------------------------------- InputPosition Iteration -------------------------------- 4 6 ---------------- ID Iteration ------

我有一个结果集,我将为它提供一个输入位置和一个用于迭代的数字。我期望最终的结果

-------------
ID        
-------------
1
2
3
4
5
6
7

--------------------------------
InputPosition     Iteration
--------------------------------
4                 6

----------------
ID   Iteration   
----------------
1    5           
2    6 (EndPosition = 2)      
3 
4    1  
5    2
6    3
7    4

因此,我需要获取此场景的“结束位置”。

我不确定这些表对手头的任务有多重要。如果答案不太正确,以下几点可能对您有用:

declare @input as int = 4
declare @itemCount as int = 7
declare @iterations as int = 6

select
    case when (@input + @iterations - 1) % @itemCount = 0 then 7
    else (@input + @iterations - 1) % @itemCount
end as EndPosition

如果表很重要,则可以将此逻辑与row_number()函数结合使用。

这将仅适用于序列号集

declare @table table (id int)
insert into @table (id)
values
(1),
(2),
(3),
(4),
(5),
(6),
(7)

declare @inputPosition int = 4
declare @iteration int = 6

;with cte as(
select 
    id,
    row_number() over (order by case when id = @inputPosition then 1 else @inputPosition +1 end) as rn
from @table)

select
    *
from
    cte
where rn = @iteration

我不太了解你需要什么。你能换一种解释吗?如何使用input&iteration来获取结束位置?在本例中,我获取了开始迭代的“InputPosition”,并遍历“ID”结果集中的记录,找出迭代结束的位置。“结束位置”是我想要的。迭代可以大于行数吗?换句话说,您是否需要对结果进行多次循环?SQL Server的哪个版本?如果超过2012年,您可能可以使用orderby:OFFSET:FETCH方案。是的,您是对的。表在这里并不重要,但结束位置很重要。