SQL中前一列加当前列的总和

时间:2014-04-08 06:16:17

标签: sql sql-server

说我有下表:

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

我希望结果如下:

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

总计应该是当前列+之前总计的总和。

这可能在MYSQL中吗?

3 个答案:

答案 0 :(得分: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

另一个版本:

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

答案 1 :(得分:0)

试试这个

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

<强> Fiddle Demo

答案 2 :(得分:0)

我认为最简单的方法是使用subselect语句对值进行求和,如标题为SQL running total sample

的教程中所述。

我还使用CTE声明将各个等级的总和作为每行的总和。然后我在子选择语句中使用了总和

;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