PostgreSQL - 使用另一个表中的先前值更新表
Posted
技术标签:
【中文标题】PostgreSQL - 使用另一个表中的先前值更新表【英文标题】:PostgreSQL - Update table with previous values from another table 【发布时间】:2021-03-04 21:38:15 【问题描述】:我想用第二个表的总和来更新一个表
这是我要更新的表“x”。有一个起始值和一个结束值:
id | op_date | initial_value | end_value |
---|---|---|---|
1 | 2020-02-01 | 0 | 0 |
1 | 2020-02-02 | 0 | 0 |
2 | 2020-02-01 | 0 | 0 |
2 | 2020-02-02 | 0 | 0 |
表'y'保存当天的数值:
id | op_date | value_day |
---|---|---|
1 | 2020-01-29 | 500 |
1 | 2020-02-01 | 100 |
1 | 2020-02-02 | 200 |
2 | 2020-01-29 | 750 |
2 | 2020-02-01 | 100 |
2 | 2020-02-02 | 250 |
我希望结果如下所示:
id | op_date | initial_value | end_value |
---|---|---|---|
1 | 2020-02-01 | 500 | 600 |
1 | 2020-02-02 | 600 | 800 |
2 | 2020-02-01 | 750 | 850 |
2 | 2020-02-02 | 850 | 1100 |
我试过这个脚本,但是进程只是运行它并没有完成它:
UPDATE x
SET
initial_value= (select sum(y.value_day)
from public.y where
y.op_date > '2020-11-01' and y.op_date < x.op_date
and y.id = x.id),
end_value= (select sum(y.value_day)
from public.y where
y.op_date between '2020-11-01' and x.op_date
and y.id = x.id);
【问题讨论】:
【参考方案1】:您可以使用窗口功能。要了解更多窗口功能,您可以查看此link。 起初我正在编写查询以选择值。
select id,op_date,
sum(value_day) over (
partition by y.id
rows between unbounded preceding and current row
)-value_day as initial_value,
sum(value_day) over (
partition by y.id
rows between unbounded preceding and current row
) as end_value
from y
;
这是您的更新查询。
UPDATE x
set initial_value=s_statement.initial_value,
end_value=s_statement.end_value
from
(select id,op_date,
sum(value_day) over (
partition by y.id
rows between unbounded preceding and current row
)-value_day as initial_value,
sum(value_day) over (
partition by y.id
rows between unbounded preceding and current row
) as end_value
from y) s_statement
where x.id=s_statement.id
and x.op_date=s_statement.op_date
;
让我知道你是否可以。
【讨论】:
很好,感谢您的回答。它对我帮助很大。以上是关于PostgreSQL - 使用另一个表中的先前值更新表的主要内容,如果未能解决你的问题,请参考以下文章
表中的递增/递减计数值取决于使用 postgresql 中的触发器插入/删除另一个表的特定列值
如何从 PostgreSQL 中的另一个表中更新具有随机 id 的表
在 PostgreSQL 中使用 executemany() 在另一个表中插入外键
根据 postgresQL 中的时间戳将值从一个表映射到另一个表