測試表和測試數據
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
這正是我所做的。儘管這個解決方案可能或可能不是像我第一次提到的那樣最好的方法,但這對我的兩個問題都是最好的解決方案 – Shay 2011-04-14 12:57:02