【问题标题】:Select a new column based on values of two column from two tables with null if no data is present如果不存在数据,则根据两个表中的两列的值选择一个新列,如果没有数据,则为 null
【发布时间】:2021-10-16 19:00:34
【问题描述】:

如果没有数据,如何根据两个表中两列的值选择一个新列,如果没有数据,则为空。

我有两张桌子

table1 与 column1 和 table2 与 column2。我需要从 column3 中的这两列中选择数据(column3 将是 table1 的一部分),其方式是:

column1     column2     column3
-------     -------     -------
1           2           null
2           3           present
3                       present
4                       null

如果 column2 的值存在于 column1 中

=> 我需要能够在 column3 中分配一个字符串(比如说“present”)

否则 column3 中的值应为 null

目前我正在使用 join 但我无法将 null 部分分配给 column3

提前致谢。

【问题讨论】:

    标签: sql apache-spark apache-spark-sql


    【解决方案1】:
     create table table1(column1 int);
     create table table2(column2 int);
    
     insert into table1 values(1);
     insert into table1 values(2);
     insert into table1 values(3);
     insert into table1 values(4);
     
     insert into table2 values(2);
     insert into table2 values(3);
    

    查询:

     select column1, (case when column2 is not null then 'Present' else Null end) Column3 
     from table1 left join table2 on column1=column2
    

    输出:

    column1 Column3
    1 null
    2 Present
    3 Present
    4 null

    db小提琴here

    【讨论】:

      【解决方案2】:

      如果 col1 和 col2 没有重复值,则可以使用:

      select t1.col1 , case when t2.col2 is not null then 'present' else null end 
      from table1 t1
      left join table2 t2
      on t1.col1 = t2.col2 
      

      【讨论】:

        猜你喜欢
        • 2012-12-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-20
        • 2020-11-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多