我想计算表中的连续行总数,但是总数必须重新开始以获取新ID
我的代码:
set @csum := 0;
select ID, name, marks, (@rt := @rt + marks) as Running_total from students order by ID;
输出返回总数,但不会打破或重新获得新ID
答案 0 :(得分:0)
尝试一下...已在MSSQL上进行测试。
select ID, name, marks,
marks + isnull(SUM(marks) OVER ( PARTITION BY ID ORDER BY ID ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) ,0) as Running_total
from students
答案 1 :(得分:0)
您需要按ID对运行总计进行分区。运行总计始终需要某个列的顺序,该顺序取决于您要计算运行总计的顺序。假设每个ID下的跑步总数基于标记的ORDER,
方法1 :如果您的DBMS支持分析功能,则可以用简单的查询形式编写
SELECT ID
,name
,marks
,Running_total = SUM(marks) OVER (PARTITION BY ID ORDER BY marks ASC)
FROM students
方法2 :如果您的数据库版本/ DBMS本身不支持分析功能,则可以使用OUTER APPLY
SELECT S.ID
,S.name
,S.marks
,Running_total = OA.runningtotalmarks
FROM students S
OUTER APPLY (
SELECT runningtotalmarks = SUM(SI.marks)
FROM students SI
WHERE SI.ID = S.ID
AND SI.marks <= S.marks
) OA;
注意:-以上查询已通过MS SQL Server的测试。