我需要对列执行一个简单的减法运算,并将新值插入到新的table.column中。
表的结构是这样的,逻辑不是一列,我只想在数学上做时间而不是日期,删除它也很好,但日期和时间是在同一个单元格中粘在一起的:
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的每一行,并将该值更新为tableab.new_time?
-----编辑----
@克林
这是我模仿你的剧本:
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;
最佳答案
您可以在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;
关于sql - 如何执行UPDATE +数学函数为空列?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39778729/