如果第一个条件失败,则在条件较少的另一列上执行sql联接

iyfamqjs  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(410)

我有一个表,表1有以下列:

我还有一个表(表2)包含以下列

我想用以下逻辑将表1与表2左连接起来:

i) try to match on 
table2.zipcode = (table1.loc_zip_cd if table1.loc_zip_cd is not null 
                 or table1.set_cip_cd if table1.loc_zip_cd is null)
and
table1.year = table2.year and
table1.category = table2.category

如果join在右侧返回null,并带有上述条件,

ii) try to match on
table1.year = table2.st_year
table1.category = table2.category

.. ..
我该如何做到这一点?这里是我的尝试使用合并,但它没有工作。。

get_results = spark.sql(""" select table1.*,table2.zipcode, table2.factor_ppqqrr from table1

                left join table2 on

                COALESCE(table1.year= table2.year and
                table1.category=table2.category and
                table2.zipcode =
                CASE
                    WHEN table1.loc_zip_cd IS NOT NULL THEN SUBSTRING(table1.loc_zip_cd,1,3)
                    WHEN table1.set_zip_cd IS NOT NULL THEN SUBSTRING(table1.set_zip_cd,1,3)
                END, 
                table1.year= table2.st_year and
                table1.category=table2.category)

                """)
qfe3c7zg

qfe3c7zg1#

加入两次,然后选择您的首选列:

SELECT
  COALESCE(t2a.year, t2b.year),
  COALESCE(t2a.column_you_prefer, t2b.column_youll_accept),
FROM
  table1
  LEFT JOIN table2 t2a
  ON  
    t2a.zipcode = COALESCE(table1.loc_zip_cd, table1.set_cip_cd) AND
    t2a.year = table1.year AND
    t2a.category = table1.category

  LEFT JOIN table2 t2b
  ON
    t2b.year = table1.year AND
    t2b.category = table1.category

相关问题