两个表之间的PostgreSQL滞后函数

两个表之间的PostgreSQL滞后函数,postgresql,Postgresql,我是Postgresql/Python新手,请耐心等待! 假设我们有两张桌子: 具有itemid、价格和时间的item表 具有colums用户ID、itemid、timecreated、quantity、firstprice、lastprice、difference的用户表。 下表举例如下: 项目表: itemid price time RBK 92 1546408800 LBV 51 1546408800 ZBT 49 1546408800 GLS

我是Postgresql/Python新手,请耐心等待! 假设我们有两张桌子:

  • 具有itemid、价格和时间的item表
  • 具有colums用户ID、itemid、timecreated、quantity、firstprice、lastprice、difference的用户表。 下表举例如下:
  • 项目表:

    itemid  price   time
    RBK      92 1546408800
    LBV      51 1546408800
    ZBT      49 1546408800
    GLS      22 1546408800
    DBC      17 1546408800
    RBK      91 1546495200
    LBV      55 1546495200
    ZBT      51 1546495200
    GLS      24 1546495200
    DBC      28 1546581600
    RBK     108 1546581600
    LBV      46 1546581600
    ZBT      49 1546581600
    GLS      21 1546581600
    DBC     107 1546581600
    
    在item表中,所有这些值都是api提供的。 和用户表:

       userid   itemid  timecreated quantitty   firstprice  currentprice difference
        1       RBK       1546408800    20      
        2       RBK       1546408800    15      
        3       RBK       1546408800    35      
        3       GLS       1546408800    101     
        3       DBC       1546495200    140     
        1       RBV       1546495200    141     
        2       RBK       1546495200    25      
        2       RBV       1546581600    31      
    
    用户表是基于djangobased的表,用户可以注册\添加新项目以跟踪价格

    我的任务是访问item表以获取具有相同时间戳的第一个价格。在该示例中,userid 1 RBK First price(1546408800)必须填充92

    我用postgresql(lag)做了一些技巧,但这似乎不起作用:

    update user
        set firstprice = tt.prev_price
        from (select item.*,
                     lag(price) over (partition by itemid order by time) as prev_price
              from item
             ) tt
        where tt.id = item.id and
              tt.prev_close is distinct from item.price;
    

    我可以从api调用当前价格,但没有找到从item表填充firstprice的方法。我将为这个查询设置触发器。我在谷歌和stackoverflow上搜索,但找不到任何对我有帮助的东西。提前感谢。

    我可以建议下一种方法(可能不是最快的):

    它使用子查询计算firstprice。测试这个

    update "user" set firstprice = (
      select price from "item" i 
      where i.itemid = "user".itemid and i.time >= "user".timecreated order by i.time limit 1
    );