Тестовая таблица и тестовые данные
declare @T table (ID int, ClientID int, [Date] datetime, Amount money)
insert into @T values
(1, 1, '1/1/2011', 10),
(2, 1, '2/1/2011', 20),
(3, 1, '3/1/2011', 30),
(4, 1, '4/1/2011', 40),
(5, 2, '1/1/2011', 10),
(6, 2, '2/1/2011', 20),
(7, 2, '3/1/2011', 30)
Получить третий ряд не так сложно.Это то же самое, что и решение с предоставленным a_horse_with_no_name.
declare @Row int = 3
;with cte as
(
select *,
row_number() over(partition by ClientID order by [Date]) as rn
from @T
)
select *
from cte
where rn = @Row
Получить строку, когда сумма бега превышает значение, немного сложнее.Вот версия цикла, использующая временную таблицу для обновления промежуточной суммы.
declare @sum money = 30
select *, cast(0 as money) as Running
into #T
from @T
declare @rn int = 1
;with cte as
(
select
Running,
Amount,
row_number() over(partition by ClientID order by [Date]) as rn
from #T
)
update cte set
Running = Amount
where
rn = @rn
while @@rowcount >= 1
begin
set @rn = @rn + 1
;with cte as
(
select
Running,
Amount,
row_number() over(partition by ClientID order by [Date]) as rn
from #T
)
update cte set
Running = Running + Amount
where rn = @rn
end
;with cte as
(
select *,
row_number() over(partition by ClientID order by [Date]) as rn
from #T
where Running >= @sum
)
select *
from cte
where rn = 1
drop table #T