SQL:比较另一个表中是否存在值,反之亦然

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

我有两个表:

**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 

我想将表1的COD列与表2的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 compare
3个回答
0
投票

您可以在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;

0
投票

您可以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

0
投票

感谢您的快速回复!

[我在Microsoft Access中尝试了这两个代码,但是它报告了错误

(case when t1.cod_1 is not null then 'Yes' else 'No' end) 

表示缺少操作员。 Access是否支持CASE WHEN?

© www.soinside.com 2019 - 2024. All rights reserved.