1

Say I have the table below:

 Id     Grade 1    Grade 2    Grade 3
  1       1           1         1  
  2       5           0         0
  3       3           1         5

I want the result as exactly as follows:

 Id     Grade 1    Grade 2    Grade 3      Total
  1       1           1         1            3
  2       5           0         0            8
  3       3           1         5            17

Total should be the sum from the current column + the previous total.

Is that possible in MYSQL?

fancyPants
  • 50,732
  • 33
  • 89
  • 96

3 Answers3

5
select
t.*,
@rolling_sum := @rolling_sum + `Grade 1` + `Grade 2` + `Grade 3` AS Total
from
Table1 t
, (select @rolling_sum := 0) var_init
order by id

Another version:

select t.*,
(select sum([Grade 1] + [Grade 2] + [Grade 3]) from Table1 sub_t where sub_t.id <= t.id)
from Table1 t
order by id
fancyPants
  • 50,732
  • 33
  • 89
  • 96
0

Try this

SELECT A.*, (@runtot := @runtot + `Grade 1` + `Grade 2` + `Grade 3`) AS Total
FROM Table1 A
,(SELECT @runtot:=0) c

Fiddle Demo

Vignesh Kumar A
  • 27,863
  • 13
  • 63
  • 115
0

I think the easiest method is summing values with a subselect statement as follows as described at tutorial titled SQL running total sample

I also used a CTE statement to sum of individual grades as the sum of each line. Then I used the sum in the sub-select statement

;with cte as (
    select
        id,
        grade1,
        grade2,
        grade3,
        isnull(grade1,0) + isnull(grade2,0) + isnull(grade3,0) as linetotal
    from grade
)
select *, total = (select sum(ss.linetotal) from cte ss where ss.id <= cte.id)
from cte
Eralper
  • 6,461
  • 2
  • 21
  • 27