sql - 是否可以编写一个基于列的运行总计进行分组的 sql 查询?

标签 sql sql-server-2005 tsql

用一个例子来解释会更容易。假设我想每组最多获得 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/

相关文章:

mysql - 添加到字符串末尾的 SQL 命令

javascript - 如何使用 node.js 在 mySQL 中插入数组中的多条记录

SQL Server 2005 - 如何找出哪些事务日志文件已恢复

tsql - 记录组的类似身份的自动递增 ID

c# - SQL 服务器 : position based on marks

php - 如何获取不同表中两个字段的总和?

php - mysql与php在表中添加一行

database - 使用 DTS 时将 Access 查询转换为 SQL Server View

sql-server - 有没有办法将 varchar 列索引为日期时间?

sql - 顺序或并行启动存储过程