我需要一些关于update语句的建议来填充表的run的一列。我使用的是mysql 5.6.25-。请查看下表和数据脚本。
create table test (symbol varchar(2), sym_date date, amount int, diff_amt int PRIMARY KEY (symbol,sym_date)) engine=InnoDB;
insert into test(symbol,sym_date, amount) values('A','2015-07-01',200);
insert into test(symbol,sym_date, amount) values('A','2015-07-02',100);
insert into test(symbol,sym_date, amount) values('A','2015-07-03',500);
insert into test(symbol,sym_date, amount) values('A','2015-07-04',800);
insert into test(symbol,sym_date, amount) values('B','2015-07-03',300);
insert into test(symbol,sym_date, amount) values('B','2015-07-05',500);
insert into test(symbol,sym_date, amount) values('B','2015-07-06',600);
insert into test(symbol,sym_date, amount) values('C','2015-07-09',100);
insert into test(symbol,sym_date, amount) values('C','2015-07-11',100);
insert into test(symbol,sym_date, amount) values('C','2015-07-12',100);
我需要基于符号的结果集与符号之间的金额列之间的差异,sym_date在剩余列diff_amt中按升序排列。
select symbol, sym_date, amount from test order by symbol, sym_date;
It will give me this result set.
symbol sym_date amount
----------------------------
A 2015-07-01 200
A 2015-07-02 100
A 2015-07-03 500
A 2015-07-04 800
B 2015-07-03 300
B 2015-07-05 500
B 2015-07-06 600
C 2015-07-09 100
C 2015-07-11 100
C 2015-07-12 100
我需要将diff_amt列填充为结果集中的差异。对于每个符号,其第一个值将相同。下一行将是第二个值 - 第一个值,它将给出结果r1。下一行将是第3个值 - r1和contiue相同。
Expected result set will be as below:
symbol sym_date amount diff_amt
-------------------------------------------------
A 2015-07-01 200 200 -- (ar1 = A1)
A 2015-07-02 100 -100 -- (ar2 = A2 - ar1)
A 2015-07-03 500 600 -- (ar3 = A3 - ar2)
A 2015-07-04 800 200 -- (ar4 = A4 - ar3)
B 2015-07-03 300 300 -- (br1 = B1)
B 2015-07-05 500 200 -- (br2 = B2 - br1)
B 2015-07-06 600 400 -- (br3 = B3 - br2)
C 2015-07-09 100 100 -- (cr1 = C1)
C 2015-07-11 100 0 -- (cr2 = C2 - cr1)
C 2015-07-12 100 100 -- (cr3 = C3 - cr2)
这只是示例场景。我正在寻找申请大桌的一般解决方案。
答案 0 :(得分:2)
您可以使用变量执行此操作。我认为以下是逻辑:
select t.*,
(@val := if(@s = symbol, amount - @val,
if(@s := symbol, amount, amount)
)
) as diff_amount
from test t cross join
(select @s := '', @val := 0) params
order by symbol, sym_date;