Rac*_*hel 3 sql t-sql sql-server-2005
用一个例子来解释会更容易.假设我想每组最多获得5个项目.
我的输入将是一个如下所示的表格:
Item Count A 2 A 3 A 3 B 4 B 4 B 5 C 1
我想要的输出看起来像这样:
Item Count A 5 A>5 3 B 4 B>5 9 C 1
我也可以使用另一种输出
Item Count RunningTotal A 2 2 A 3 5 A 3 8 B 4 4 B 4 8 B 5 13 C 1 1
我可以ROW_NUMBER()用来获取每组中的前X个记录,但我的要求是获得每个组的前X项,而不是X记录.我的想法是如何做到这一点空白.
declare @yourTable table (item char(1), [count] int)
insert into @yourTable
select 'A', 2 union all
select 'A', 3 union all
select 'A', 3 union all
select 'B', 4 union all
select 'B', 4 union all
select 'B', 5 union all
select 'C', 1
;with cte(item, count, row) as (
select *, row_number() over ( partition by item order by item, [count])
from @yourTable
)
select t1.Item, t1.Count, sum(t2.count) as RunningTotal from cte t1
join cte t2 on t1.item = t2.item and t2.row <= t1.row
group by t1.item, t1.count, t1.row
Run Code Online (Sandbox Code Playgroud)
结果:
Item Count RunningTotal
---- ----------- ------------
A 2 2
A 3 5
A 3 8
B 4 4
B 4 8
B 5 13
C 1 1
Run Code Online (Sandbox Code Playgroud)