Insert into and replace old records with new

Viewed 63

I have a table which takes data with sqoop and every day it will be truncated.

This tblSqoop at the beginning has these values :

+----+-------+--------------+---------------+---------+--------+
| id | names | created_date | modified_date | country | number |
+----+-------+--------------+---------------+---------+--------+
| 33 | nick  | 1/1/2020     | 1/1/2020      | Dubai   | 1234   |
| 45 | ted   | 2/7/2020     | 2/7/2020      | Spain   | 12345  |
+----+-------+--------------+---------------+---------+--------+

And parses with insert into tblMaxed.

Next day tblSqoop has this data:

 +----+-------+--------------+---------------+---------+--------+
| id | names | created_date | modified_date | country | number |
+----+-------+--------------+---------------+---------+--------+
| 33 | nick  | 1/1/2020     | 12/31/2020    | Dubai   | 1234   |
| 45 | ted   | 2/7/2020     | 8/19/2020     | Spain   | 12345  |
| 45 | ted   | 2/7/2020     | 9/12/2020     | Spain   | 12345  |
| 45 | ted   | 2/7/2020     | 10/11/2020    | Spain   | 12346  |
| 45 | ted   | 2/7/2020     | 1/1/2021      | Spain   | 12345  |
+----+-------+--------------+---------------+---------+--------+

What I want is to have inside tblMaxed the latest info like:

+----+-------+--------------+---------------+---------+--------------------+
| id | names | created_date | modified_date | country | number |status_date|
+----+-------+--------------+---------------+---------+--------+-----------+
| 33 | nick  | 1/1/2020     | 12/31/2020    | Dubai   | 1234   |12/31/2020 |
| 45 | ted   | 2/7/2020     | 10/11/2020    | Spain   | 12346  |10/11/2020 |
| 45 | ted   | 2/7/2020     | 1/1/2021      | Spain   | 12345  |1/1/2021   |
+----+-------+--------------+---------------+---------+--------+-----------+

I am running this:

insert into tblMaxed 
select 
id,
names,
created_date,
modified_date,
country,
number,
MAX(modified_date) as status_date
from tblSqoop
group by id,
names,
created_date,
modified_date,
country,
number

But as a result I take all the records again. Will help the use of a PK ?

1 Answers

could you pls truncate the table and reload tblMaxed using this ? (Explanation is in the code)

select 
id,
names,
created_date,
modified_date,
country,
number,
modified_date as status_date
FROM 
(select  t.*, row_number() OVER (PARTITION BY id,number  Order by  id,number , modified_date desc) rn from tblSqoop t) rs 
where rs.rn=1 -- This will pick up data for MAX modified_date from sqoop table
Related