Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql SQL上一条目的总和_Mysql_Sql_Sum - Fatal编程技术网

Mysql SQL上一条目的总和

Mysql SQL上一条目的总和,mysql,sql,sum,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 ?????) grou

我有一张桌子:

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
我试过这样的方法:

2013   0
2014   4
2015   18
2016   22
2017   29
select year, sum(val) from 
(select year, val from table ?????)
group by year
也许在某个地方应该有一个内部连接

试试看

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

你的问题有点挑战性,因为你第一年想要
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;

如果只想使用旧年份,请使用此查询

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

但是,最新的数据不需要子查询,只需选择year和sum(val),然后按年份分组即可轻松完成

您没有主键。随着时间的推移,这可能会被证明是有问题的。我最终使用了这个答案,因为它是唯一一个没有使用变量的答案。谢谢