【问题标题】:Map values from one table to another table based on timestamp in postgresQL根据 postgresQL 中的时间戳将值从一个表映射到另一个表
【发布时间】:2021-11-08 00:27:29
【问题描述】:

我有两张桌子。存储特定日期价格的交易表(带有精确的时间戳)。还有一个价格历史表,我们每天都有一行。 我现在想将交易表中的价格放在时间戳匹配的价格历史表中(同一天)。下面的照片应该有助于澄清我需要什么。价格历史表中的价格列是需要的结果。

【问题讨论】:

    标签: sql postgresql time-series


    【解决方案1】:

    一个简单的连接应该在这里工作:

    SELECT t.date, ph.price
    FROM Transactions t
    INNER JOIN "price-history" ph
        ON ph.date = t.date::date
    

    这假定price-history 表类似于日历表,并且包含每个感兴趣日期的数据。如果不是,那么我们应该修改上面的内容以使用左连接,并且我们应该选择COALESCE(ph.price, 0) 而不是仅仅ph.price

    【讨论】:

    • 类日历表条件的良好提示。
    【解决方案2】:

    更新表,您可以使用:

    update price_history ph
        set price = t.price
        from transactions t
        where t.date::date = ph.date;
    

    注意:如果同一日期有两笔交易,则使用任意一笔进行更新。

    如果你需要构造价格历史表,你可以先用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);
    

    然后更新上面的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      相关资源
      最近更新 更多