简体   繁体   中英

Getting column_name different in two tables

I have two following tables with similar structure with id1 and id2 as unique:

             Table1
id1    id2   amt1    amt2    id3
1A      1     12      14     12A
2A      4     23      35     34V
3A      8     45      23     13D
.................................

            Table2
id1    id2   amt1    amt2    id3
1A      1     12      27     12A
2A      4     67      35     34D
3A      8     45      23     13D


.................................

So id1 and id2 are unique here so what i wanted to create a query to which tells me for which id which amt is not matching so i made i simple script like this:

select T.id1,T.id2,
T.amt1,      P.amt1,
T.amt2,      P.amt2,
T.id3,       P.id3
from 
Table1 T,
Table2 P
where 
T.id1=P.id1
T.id2=P.id2
(
nvl(T.amt1 ,0)-nvl(P.amt1 ,0)<>0 OR      --used nvl to check if one table has null for other tables's number
nvl(T.amt2 ,0)-nvl(P.amt2 ,0)<>0 OR
T.id3  <>P.id3  
);

This gives me the difference but i becomes difficult to analyze on large tables and suppose i had lot of columns and amounts and lot of differences i want to see the output in a format shown below: Suppose i am looking for differences in Table1

id1  id2  difference in column
1A    1       amt2
2A    4       amt1,id3

Can anybody show what query can generate output like as shown above.

use the following query and test:

select * from (select T.id1,T.id2,
T.amt1,      P.amt1,
T.amt2,      P.amt2,
T.id3,       P.id3
decode(nvl(T.amt1 ,0)-nvl(P.amt1 ,0),0,'','amt1')||' '||decode(nvl(T.amt2 ,0)-nvl(P.amt2 ,0),0,'','amt2')||' '||decode(nvl(T.id3 ,0),nvl(P.id3 ,0),'','ID3') difference_in_col
from 
Table1 T,
Table2 P
where 
T.id1=P.id1
and T.id2=P.id2
) where difference_in_col is not null;

This is assuming that you have only limited known number of columns to be checked.

if not then you will have to go for a procedure script to populate a table or show you the result in dbms_output.

that will have to be made too dynamic. depends on requirement

How about the following hideous beast of convoluted (and untested) SQL?

select id1
      ,id2
      ,decode(a.amt1, b.amt1, null, 'amt1,') ||
       decode(a.amt2, b.amt2, null, 'amt2,') || 
       decode(a.id3,  b.id3,  null, 'id3,') as difference_in_column
  from table1 a
  join table2 b using(id1, id2)
 where decode(a.amt1, b.amt1, 1, 0) = 0
    or decode(a.amt2, b.amt2, 1, 0) = 0
    or decode(a.id3,  b.id3,  1, 0) = 0;

Note 1. I used the decode() construct because it treats null as equal to null.

Note 2. You can change to FULL OUTER JOIN if you also want to find rows in table1 that does not exist in table2 or vice verca.

Note 3. I haven't removed the trailing comma in the list.

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