更新/插入SQL中的表

时间:2015-08-10 20:51:40

标签: sql sql-server sql-update upsert

我有两张桌子:

表A

column0 int identity,
Key1 varchar(50),
Key2 varchar(50),
Column3 varchar(50)

表B

Key1 varchar(50),
Key2 varchar(50),
Column3 varchar(50)

现在我必须从TableB插入/更新到TableA,具体取决于Key1Key2列。也不是TableA中的所有记录都可以考虑。

需要考虑仅按key1,key2分组时具有MAX标识(column0)值的记录。

1 个答案:

答案 0 :(得分:0)

请尝试以下查询:

--update part
update b
set b.Column3=t.Column3
 tblB b inner join
 (select *, row_number() over(partition by Key1,Key2 order by Column0 desc)  as r from tblA) t 
on t.Key1=b.Key1 and t.Key2 =b.key2
where r=1 
--insert part
insert into tblB(Key1,Key2,Column3)
Select t.key1,t.Key2,t.Column3 
from tblB b right join
 (select *, row_number() over(partition by Key1,Key2 order by Column0 desc)  as r from tblA) t 
on t.Key1=b.Key1 and t.Key2 =b.key2
where r=1 and b.Key1 is NULL and b.Key2 is NULL