【问题标题】:How can I perform a left join comparing two months columns and getting the one right after the other?如何执行左连接比较两个月的列并获得一个接一个的列?
【发布时间】:2020-06-03 14:39:39
【问题描述】:

事情是这样的,我必须参加桌子,我想加入他们。但是,我想根据一个平等和另一个比较来带来价值。就像我想在两个表中的 id 相同并且表 1 中的另一列必须低于表 2 的同一列时带来值。这是我的两个表:

表1(销售表):

id    produts_sold    month
A1    100             '2020-01-01'
A3    500             '2020-01-01'
A1    100             '2020-02-01'
A2    300             '2020-02-01'
A3    200             '2020-02-01'
A1    400             '2020-04-01'
A2    500             '2020-04-01'
A1    400             '2020-06-01'
A1    500             '2020-08-01'

表 2(价格表 - 显示价格更新时间)

id    price    month
A1    100      '2019-12-01'
A2    200      '2019-12-01'
A3    300      '2019-12-01'
A1    200      '2020-02-01'
A1    400      '2020-03-01'

事情是这样的,我想为我的桌子带来价格更新。但是我没有每个月的价格,就在它更新的时候。基本上,我的决赛桌是这样的:

id    produts_sold    month             price
A1    100             '2020-01-01'      100
A3    500             '2020-01-01'      300
A1    100             '2020-02-01'      200
A2    300             '2020-02-01'      200
A3    200             '2020-02-01'      300
A1    400             '2020-04-01'      400
A2    500             '2020-04-01'      200
A1    400             '2020-06-01'      400
A1    500             '2020-08-01'      400

这是我迄今为止尝试过的:

select t1.*, t2.price
   from table_1 t1
   left join table_2 t2
        on t1.id=t2.id and t1.month > t2.month

但是,这并不好。由于 2 月 20 日在 12 月 19 日之后,但 4 月 20 日也在 12 月 19 日之后,我可能会得到 3 月的 4 月价格,而不是 2 月的价格。我怎样才能让这个左连接正确?

【问题讨论】:

    标签: sql postgresql join left-join


    【解决方案1】:

    您可以使用横向连接:

    select t1.*, t2.price
    from table_1 t1 left join lateral
         (select t2.*
          from table2 t2
          where t2.id = t1.id and t2.month < t1.month
          order by t2.month desc
          limit 1
         ) t2
         on true;
    

    请注意,在进行此类比较时,通常会使用&lt;= 而不是&lt;

    在这种情况下,您还可以使用相关子查询:

    select t1.*,
           (select t2.price
            from table2 t2
            where t2.id = t1.id and t2.month < t1.month
            order by t2.month desc
            limit 1
           ) as price
    from table_1 t1;
    

    【讨论】:

    • 这真的是 PostgreSQL 的东西吗?我问它是因为我在“横向”上得到红色并收到错误消息:无效操作:“选择”处或附近的语法错误
    • @DumbML 。 . .自很久以前(2014 年 12 月)版本 9.4 (postgresql.org/docs/9.4/queries-table-expressions.html) 以来,它一直是 Postgres 的一部分。我还应该注意,它也是标准 SQL。
    猜你喜欢
    • 1970-01-01
    • 2022-09-27
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 2014-07-30
    • 2014-02-03
    • 2020-08-25
    • 1970-01-01
    相关资源
    最近更新 更多