如何使用分区(或其他方式)联接两个表

问题描述 投票:0回答:1

我有两个表:

  • 具有每天销售信息的销售产品(test1,test2)的表A
  • 具有此产品类别更改历史记录的表B(产品可能在一年或每天更改类别,这取决于产品)

并且我想在当日使用当前产品类别进行销售(如果今天类别更改,我希望在下一天更改之前的这一天和第二天进行销售)

请在没有很多子查询的情况下帮助您(表很重)

    TABLE A >>
        uid  name  date
        1   test1  2019-09-01
        2   test1  2019-09-02
        3   test1  2019-09-03
        4   test2  2019-09-01
        5   test2  2019-09-02
        6   test2  2019-09-03

    TABLE B >>
    uid  name  date_change  category
    1   test1  2019-08-30  cat1
    2   test1  2019-09-02  cat2
    4   test1  2019-09-04  cat3
    5   test2  2019-09-01  cat4
    6   test2  2019-09-03  cat5

    TABLE Result >>
    uid  name  date       date_change  category
    1   test1  2019-09-01  2019-08-30  cat1
    2   test1  2019-09-02  2019-09-02  cat2
    3   test1  2019-09-03  2019-09-02  cat2
    4   test2  2019-09-01  2019-09-01  cat4
    5   test2  2019-09-02  2019-09-01  cat4
    6   test2  2019-09-03  2019-09-03  cat5


mysql sql postgresql google-bigquery
1个回答
0
投票

一个选项使用相关子查询从catb之前的date中检索最新的a

select 
    a.*,
    (
        select cat 
        from b 
        where b.name = a.name and b.date_changed <= a.date 
        order by b.date_changed desc 
        limit 1
    ) cat
from a
© www.soinside.com 2019 - 2024. All rights reserved.