【问题标题】:SQL: Compare if a value exist in another table and vice versaSQL:比较一个值是否存在于另一个表中,反之亦然
【发布时间】:2020-08-28 10:18:15
【问题描述】:

我有两张桌子:

**Table1**

COD_1    DATE
001      05/10/2020
002      05/11/2020
003      05/12/2020

**Table2**

COD_2   Date
001     12/12/2008 
002     12/11/2008 
008     12/09/2008 

我想将 Table1 的 COD 列与 Table2 的 COD 列进行比较。这两列的每个值都不会重复。 所以我想创建第三个表来显示 COD、名为 col_Table1 和 col_Table2 的两列以及它们各自的日期。这些列(col_Table1 和 col_Table2)中的每一个都通知相应的 COD 是在表 1 中还是在表 2 中,或者在两个表中。 决赛桌应该是这样的:

COD_newTable    col_Table1  col_Table2  DATE_table1  DATE_table2
001              Yes         Yes        05/10/2020   12/12/2008
002              Yes         Yes        05/11/2020   12/11/2008
003              Yes         No         05/12/2020
008              No          Yes                     12/09/2008

有人可以帮帮我吗?

【问题讨论】:

    标签: sql ms-access join group-by pivot


    【解决方案1】:

    您可以在 SQL Server 中使用full join

    select coalesce(t1.cod_1, t2.cod_2) as cod,
           (case when t1.cod_1 is not null then 'Yes' else 'No' end) as in_1,
           (case when t2.cod_1 is not null then 'Yes' else 'No' end) as in_2,
           t1.date as date_1,
           t2.date as date_2
    from table1 t1 full join
         table2 t2
         on t1.cod_1 = t2.cod_2;
    

    【讨论】:

      【解决方案2】:

      你可以full join:

      select
          coalesce(t1.cod_1, t2.cod_2) cod_new_table,
          case when t1.cod_1 is null then 'No' else 'Yes' end col_table1,
          case when t2.cod_2 is null then 'No' else 'Yes' end col_table2,
          t1.date date_table1,
          t2.date date_table2
      from table1 t1
      full join table2 t2 on t1.cod_1 = t2.cod_2
      

      您最终用它标记问题的 MS Access 既不支持 full join 也不支持 case。对于您的数据集,另一种选择是union alliif() 的条件聚合:

      select
          cod_new_table,
          max(iif(which = 1, 'Yes', 'No')) col_table1,
          max(iif(which = 2, 'Yes', 'No')) col_table2,
          max(date_table1) date_table1,
          max(date_table2) date_table2
      from (
          select 1 which, cod_1 cod_new_table, date date_table1, null date_table2 from table1
          union all
          select 2, cod_2, null, date from table2
      ) t
      group by cod_new_table
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-09-11
        • 2016-09-03
        • 2019-02-19
        • 1970-01-01
        • 1970-01-01
        • 2022-12-20
        • 1970-01-01
        • 2016-02-27
        相关资源
        最近更新 更多