我需要对列执行简单的减法并将新值插入新的table.column。
这个表的结构是这样的,逻辑不是一个列,它是我想要的数学上只是时间而不是日期,丢弃它也很好,但日期和时间是在同一个单元格粘在一起:< / p>
Table A
A Time (Logic)
1 aaa YYYY-MM-DD HH:MM:SS (row2 - row1)
2 aaa YYYY-MM-DD HH:MM:SS (row3-row2)
3 aaa YYYY-MM-DD HH:MM:SS (row4-row3)
Table B
A new_time
1 aaa insert logic row 1
2 aaa insert logic row 2
3 aaa insert logic row 3
问题是如何从下一行中减去tableA.time的每一行,并将该值更新为tableB.new_time?
----- ---- EDIT
@klin
这是我的脚本模仿你的脚本:
update tableB
set new_time = tableA.time
from (
select tableA.A- lead(tableA.A) over (order by tableB.B)
from tableA
) tableA.A
where tableB.a = tableA.A
错误讯息:
SQL Error [500310] [42P10]: [Amazon](500310) Invalid operation: subquery in FROM may not refer to other relations of same query level;
答案 0 :(得分:3)
您可以使用子查询作为update
中的数据源。例如:
create table table_a (id int primary key, t timestamp);
insert into table_a values
(1, '2016-09-01'), (2, '2016-09-02'), (3, '2016-09-04');
create table table_b (id int primary key, i interval);
insert into table_b values
(1, null), (2, null), (3, null);
update table_b b
set i = a.i
from (
select id, t - lead(t) over (order by id) i
from table_a
) a
where b.id = a.id;
select * from table_b;
id | i
----+---------
1 | -1 days
2 | -2 days
3 |
(3 rows)
单字母别名很方便但有时不太清楚。具有更多信息别名的相同查询:
update table_b as alias_b
set i = subquery.i
from (
select id, t - lead(t) over (order by id) i
from table_a
) as subquery
where alias_b.id = subquery.id;