-2

I want to compute running row totals across a table, however the totals must start over for new IDs

https://i.stack.imgur.com/8UDwZ.jpg

My code:

set @csum := 0;
select ID, name, marks, (@rt := @rt + marks) as Running_total from students order by ID;

The output returns the totals however doesn't break or start over for new IDs

Snel23
  • 1,381
  • 1
  • 9
  • 19
dan71995
  • 9
  • 3

2 Answers2

0

Bro try this... It is tested on 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 
M Danish
  • 480
  • 2
  • 5
0

You need to partition your running total by ID. A running total always needs an order of some column, by ordering on which you want to calculate the running total. Assuming running total under each ID is based on ORDER of marks,

Approach 1: It can be written in a simple query if your DBMS supports Analytical Functions

SELECT     ID
           ,name
           ,marks
           ,Running_total = SUM(marks) OVER (PARTITION BY ID ORDER BY marks ASC)
FROM       students

Approach 2: You can make use of OUTER APPLY if your database version / DBMS itself does not support Analytical Functions

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;

Note:- The above queries have been tested MS SQL Server.

san
  • 1,415
  • 8
  • 13
  • @dan71995 could you please upvote the answer of it helped? – san Jun 16 '19 at 20:54
  • Hello San, i did upvote it, but stack overflow returns this message : "Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score." – dan71995 Jun 18 '19 at 04:35
  • I see. No problem :) – san Jun 18 '19 at 04:52