插入旧记录并用新记录替换旧记录



我有一个用sqoop获取数据的表,每天它都会被截断。

开头的这个tabsqoop有这些值:

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

并插入到tblmax .

第二天tblSqoop有这个数据:

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

我想要的是在tblmax里面有最新的信息,比如:

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

我正在运行这个:

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

但结果我把所有的记录都拿了一遍。会有助于PK的使用吗?

能否截断表并使用此重新加载tblMaxed?(说明在代码中)

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

最新更新