简体   繁体   中英

SQL Query to find out matching column combination between 2 tables

I would like to know the query for the following case.

Table 1 :         Table 2

Col1    Col2    Col1    Col2
Sandy    1     Sandy     24
Reena    2     Reena     32
Swathi   3     Swathi    3
Reenu    4     Karthik   5
               Reenu     4
               Muthu     6

the query should return:

  1. The rows in table 2 that is not in table 1 ( Karthik and Muthu rows should be the result)

  2. It shoudl compare the column combination and should return the changed column combination.

Finally i should get the following result : ,

Table1.Col1 Table1.col2 Table2.col2
Sandy         1          24
Reena         2          32
Karthik      NA          5
Muthu        NA          6

Thanks in advance.

select t2.col1, t1.col2, t2.col2 as t2c
from table2 t2
left join table1 t1 on t1.Col1 = t2.Col1
where t1.Col2 is null or t1.Col2 <> t2.Col2

if you want explicitely 'NA', you should do something like this (function depending on your dbms)

coalesce(<somefunctionToConvertinttostring>(t1.col2), 'NA')

sqlFiddle

Please try:

select a.Col1, a.Col2, b.Col2 
from Table2 a left join Table1 b on a.Col1=b.Col1 
where b.Col1 is null

union

select a.Col1, a.Col2, b.Col2 
from Table2 a inner join Table1 b on a.Col1=b.Col1 
where a.Col2<>b.Col2

You can concat both queries with UNION ALL :

SELECT Table1.Col1 AS T1Col1, 
       Table2.col1 AS T2Col1, 
       Table2.col2 As T2Col2
FROM Table1 INNER JOIN Table2
  ON Table1.Col1 = Table2.Col1 
WHERE Table1.Col2 <> Table2.Col2

UNION ALL 

SELECT COALESCE(Table1.Col1,'NA') AS T1Col1, 
       Table2.col1 AS T2Col1, 
       Table2.col2 As T2Col2
FROM Table2 LEFT OUTER JOIN Table1
  ON Table1.Col1 = Table2.Col1 
WHERE Table1.Col1 IS NULL

Demonstration

select c3,ISNULL(C2,'NA') AS C2,c4 from Table1 right join
Table2 on Table1 .c1 = Table2.C3 WHERE ISNULL(Table1.c2,0) <> Table2.C4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM