views:

160

answers:

2

There are two tables 1 and 2 with columns Id: unique ; timestamp:long; money:double

SOME RECORDS are missing in Table 1 and table2.

Question: try to merge both tables together with the timestamps of table1 , and if the records is only in table 2 adjust the timestamp with average time difference between table 1 and table2.

Please help me, confused very much.

+1  A: 

What DB are you using as DB:s support different merge commands. Also can you use some stored procedure?

Calmar
Oracle, I assume, since that's what it has been tagged with.
Martijn Pieters
Yes. It's oracle 10g.
Siv
+3  A: 

You don't say whether you want to merge into one of the existing tables or into a new table. But either way it is not "non-trivial".

If you want to insert the set of data from one of the existing tables into the other, use MERGE (the clue is in the question).

SQL> select * from t1;

        ID TS             MONEY
---------- --------- ----------
         1 25-JUL-09        123
         2 04-AUG-09         67

SQL> select * from t2;

        ID TS             MONEY
---------- --------- ----------
         2 08-AUG-09         67
         3 10-AUG-09        787

SQL> merge into t1
  2     using   t2
  3     on ( t1.id = t2.id )
  4     when matched then
  5          update set ts = ts + ((t2.ts - t1.ts) / 2)
  6     when not matched then
  7          insert
  8             (id, ts, money)
  9     values
 10              (t2.id, t2.ts, t2.money)
 11  /

2 rows merged.

SQL> select * from t1
  2  /

        ID TS             MONEY
---------- --------- ----------
         1 25-JUL-09        123
         2 10-AUG-09         67
         3 10-AUG-09        787

SQL>

If you want to insert both sets of data into a new table then you can do it like this:

SQL> insert all
  2      when t1_id = t2_id then
  3          into t3 values (t1_id, t1_ts + ((t2_ts - t1_ts)/2), t1_money)
  4      when t1_id is not null and t2_id is null then
  5          into t3 values (t1_id, t1_ts, t1_money)
  6      when t1_id is null and t2_id is not null then
  7          into t3 values (t2_id, t2_ts, t2_money)
  8  select t1.id as t1_id
  9         , t1.ts as t1_ts
 10         , t1.money as t1_money
 11         , t2.id as t2_id
 12         , t2.ts as t2_ts
 13         , t2.money as t2_money
 14  from t1 full outer join t2 on t1.id = t2.id
 15  /
SQL> select * from t3
  2  /

        ID TS             MONEY
---------- --------- ----------
         2 06-AUG-09         67
         1 25-JUL-09        123
         3 10-AUG-09        787

SQL>
APC
@APC.. Thank you very very much !.... I am trying it out and would update the same.
Siv
It works... thanks a ton @APC.
Siv