Share via

running sum

Shambhu Rai 1,411 Reputation points
2023-10-06T14:41:46.28+00:00

Hi Expert,

how to getting running some from col2

create table table1(col1 int)

insert into table1(10);

insert into table1(20);

insert into table1(30);

insert into table1(40);

Expected Output:

Total_col1

10

30

70

100

SQL Server Reporting Services
SQL Server Reporting Services

A SQL Server technology that supports the creation, management, and delivery of both traditional, paper-oriented reports and interactive, web-based reports.

SQL Server Integration Services
SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

GlockByte 161 Reputation points
2023-10-06T16:23:52.69+00:00
CREATE TABLE #table1(col1 int)

INSERT INTO #table1 VALUES (10),(20),(30),(40)

SELECT
	col1,
	SUM(col1) OVER (ORDER BY col1) AS [runningTotal]
FROM #table1

DROP TABLE #table1

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 84,086 Reputation points
    2023-10-06T15:15:40.2966667+00:00

    Tables have no defined order. You will need a sequence column. Then the running total is just the sum of sequences less than or equal to the current sequence.

    select 
       col1, 
       (select sum(col1) 
        from table1 t2
        Where t2.sequence <= t1.sequence) as runningTotal
    from table1 t1
    order by t1.sequence
    

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.