T-SQL查询获得结果集中的结束位置
问题描述:
我有一个结果集,我将为其提供一个输入位置和一个迭代编号。我期待结果的结果。T-SQL查询获得结果集中的结束位置
-------------
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
因此,我需要得到这个场景的'EndPosition'。
答
我不确定这些表格对手头任务有多重要。如果答案是不是很,下面可能会为你工作:
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()函数。
+0
是的,你是对的,桌子在这里并不重要,但最终的立场是。 – Prakazz
答
这将只适用于您的序号集。
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
我不是很追踪你需要什么。你能解释一下吗?如何使用输入和迭代来获得最终位置? –
在这个例子中,我得到'InputPosition',我从中开始我的迭代并遍历'ID'结果集中的记录,并找出迭代结束的位置。 '最终位置'是我正在寻找的。 – Prakazz
迭代次数是否可以大于行数?换句话说,您是否需要不止一次地循环浏览结果? – Jerrad