以前条目的SQL总和

时间:2015-07-20 12:20:27

标签: mysql sql sum

我有一张桌子:

year   val
----   ----
2013    4
2014    6
2014    2
2014    6
2015    1
2015    3
2016    7

有没有办法在表格中获得每年前几年的总和? 结果应该是这样的:

2013   0
2014   4
2015   18
2016   22
2017   29

我试过这样的事情:

select year, sum(val) from 
(select year, val from table ?????)
group by year

在某个地方应该有一个内部联接?

3 个答案:

答案 0 :(得分:1)

你的问题有点挑战,因为第一年你需要0

select year,
       ( (@p := @p + sumval) - sumval) as cumeprev
from (select year, sum(val) as sumval
      from table t
      group by year
     ) t cross join
     (select @p := 0) params
order by year;

答案 1 :(得分:1)

如果您只想过年,请使用此查询

SELECT DISTINCT year , ( SELECT SUM(val) FROM table as temp2 WHERE temp2.year < temp1.year ) as v FROM table as temp1

如果你想包括年份,那么改变temp2.​​year&lt; temp1.year to&lt; =,如果你想按年过滤,那么使用comparison =

所以

SELECT DISTINCT year , ( SELECT SUM(val) FROM table as temp2 WHERE temp2.year <= temp1.year ) as v FROM table as temp1

SELECT DISTINCT year , ( SELECT SUM(val) FROM table as temp2 WHERE temp2.year = temp1.year ) as v FROM table as temp1

但是没有子查询可以很容易地完成最新工作,只需选择年份和总和(val)然后逐年分组

答案 2 :(得分:0)

尝试

select year, @previous := @previous + sum(val)
from your_table
cross join (select @previous := 0) p
group by year
order by year