2017-05-05 42 views
2

我有一個結果集,我將爲其提供一個輸入位置和一個迭代編號。我期待結果的結果。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'。

+0

我不是很追蹤你需要什麼。你能解釋一下嗎?如何使用輸入和迭代來獲得最終位置? –

+0

在這個例子中,我得到'InputPosition',我從中開始我的迭代並遍歷'ID'結果集中的記錄,並找出迭代結束的位置。 '最終位置'是我正在尋找的。 – Prakazz

+0

迭代次數是否可以大於行數?換句話說,您是否需要不止一次地循環瀏覽結果? – Jerrad

回答

1

我不確定這些表格對手頭任務有多重要。如果答案是不是很,下面可能會爲你工作:

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

1

這將只適用於您的序號集。

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