根据 postgresQL 中的时间戳将值从一个 table 映射到另一个 table
Map values from one table to another table based on timestamp in postgresQL
我有两个 table。存储特定日期(带有精确时间戳)价格的交易 table。还有一个价格历史记录 table,其中我们每天都有一行。
我现在想将交易 table 的价格放入时间戳匹配(同一天)的价格历史记录 table 中。下面的照片应该有助于澄清我需要什么。价格历史 table 中的价格列是需要的结果。
一个简单的连接应该在这里起作用:
SELECT t.date, ph.price
FROM Transactions t
INNER JOIN "price-history" ph
ON ph.date = t.date::date
这假设 price-history
table 就像一个日历 table,并且包含每个感兴趣日期的数据。如果不是,那么我们应该修改上面的内容以使用左连接,而且我们应该 select COALESCE(ph.price, 0)
而不是 ph.price
.
要更新 table,您将使用:
update price_history ph
set price = t.price
from transactions t
where t.date::date = ph.date;
注意:如果同一天有两笔交易,则使用任意一笔进行更新。
如果您需要构造价格历史table,您可以先用0
值构造它,然后更新:
create table price_history (
date date primary key,
price numeric(10, 2) -- or whatever
);
insert into price_history (date, price)
select gs.dte, 0
from generate_series('2021-01-01'::date, '2021-12-31'::date, interval '1 day') gs(dte);
然后更新上面的值。
我有两个 table。存储特定日期(带有精确时间戳)价格的交易 table。还有一个价格历史记录 table,其中我们每天都有一行。
我现在想将交易 table 的价格放入时间戳匹配(同一天)的价格历史记录 table 中。下面的照片应该有助于澄清我需要什么。价格历史 table 中的价格列是需要的结果。
一个简单的连接应该在这里起作用:
SELECT t.date, ph.price
FROM Transactions t
INNER JOIN "price-history" ph
ON ph.date = t.date::date
这假设 price-history
table 就像一个日历 table,并且包含每个感兴趣日期的数据。如果不是,那么我们应该修改上面的内容以使用左连接,而且我们应该 select COALESCE(ph.price, 0)
而不是 ph.price
.
要更新 table,您将使用:
update price_history ph
set price = t.price
from transactions t
where t.date::date = ph.date;
注意:如果同一天有两笔交易,则使用任意一笔进行更新。
如果您需要构造价格历史table,您可以先用0
值构造它,然后更新:
create table price_history (
date date primary key,
price numeric(10, 2) -- or whatever
);
insert into price_history (date, price)
select gs.dte, 0
from generate_series('2021-01-01'::date, '2021-12-31'::date, interval '1 day') gs(dte);
然后更新上面的值。