我有这样的表格。
existing condition
+----+------+-----+
| x | a | b |
+----+------+-----+
| 1 | 3 | 0 |
| 3 | 6 | 0 |
| 7 | 2 | 0 |
| 12 | -1 | 0 |
| 16 | 8 | 0 |
| 23 | -6 | 0 |
| 28 | 4 | 0 |
+----+------+-----+
列x是日期数据类型,必须按日期排序 我的问题是,我希望列b具有满足
的值b = a + b'
其中b'是更新记录之前的值
expected condition
+----+------+------+
| x | a | b |
+----+------+------+
| 1 | 3 | 3 |
| 3 | 6 | 9 |
| 7 | 2 | 11 |
| 12 | -1 | 10 |
| 16 | 8 | 18 |
| 23 | -6 | 12 |
| 28 | 4 | 16 |
+----+------+------+
对于x = 1,b = 3,因为它是第一个数据
对于x = 3,b = 9,因为a = 6且最后b = 3所以(6 + 3)
...
对于x = 16,b = 18,因为a = 8且最后b = 10所以(8 + 10)
...
等等。
如何使用单一更新声明更新b列?
这可能吗?
答案 0 :(得分:1)
这是基本版本:
a
将变量设置为0,然后使用该变量的值更新b
字段,然后将变量更新为{{1}}字段的值。当mysql以left->右顺序评估变量用法/赋值时,a = a + @foo将使用@foo的PREVIOUS行的值。
答案 1 :(得分:0)
尝试:
update example3 target set b= acum
from
(select x, a, b, sum(a) over (order by x) as acum
from example3) source
where source.x=target.x;
它符合您的期望。
创建架构:
create table example3(
x integer primary key,
a integer,
b integer,
expected integer
);
insert into example3 (x,a,expected) values
(1 , 3 , 3 ),
(3 , 6 , 9 ),
(7 , 2 , 11 ),
(12 ,-1 , 10 ),
(16 , 8 , 18 ),
(23 ,-6 , 12 ),
(28 , 4 , 16 );
答案 2 :(得分:0)
我会这样做:
update mytable as t1
set b = (select sum(a) as acum from (select x, a from mytable) as t2 where t2.x <= t1.x)
;
请参阅此处的小提琴:http://sqlfiddle.com/#!9/7d624/1
感谢@Emilio提供样本ddl&amp;数据