测试表和测试数据
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