我有两张桌子:
表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
,具体取决于Key1
和Key2
列。也不是TableA
中的所有记录都可以考虑。
key1,key2
分组时具有MAX标识(column0)值的记录。
答案 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