用一个例子来解释会更容易。假设我想每组最多获得 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
结果:
Item Count RunningTotal
---- ----------- ------------
A 2 2
A 3 5
A 3 8
B 4 4
B 4 8
B 5 13
C 1 1
关于sql - 是否可以编写一个基于列的运行总计进行分组的 sql 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8717822/