我有如下表A和表B.两者都有帐号和ID。 我想从表A中找出表B中帐号的ID,并用表A中的ID值更新表B.我想让表A看起来像表B.如何实现这个目标?
我试过
select distinct A.ID,A.ACCTNO,B.ACCTNO from TableA as A
inner join TableB as B on A.ACCTNO = B.ACCTNO
答案 0 :(得分:0)
将JOIN
与update
一起使用。
<强>查询强>
update t1
set t1.ID = t2.ID
from TableB t1
join TableA t2
on t1.ACCTNO = t2.ACCTNO;
<强>更新强>
用于填充空行。
<强>查询强>
;with cte as( select rn = row_number() over( partition by acctno order by acctno ), * from TableB ), cte2 as( select rn = row_number() over( order by acctno ), * from TableA where not exists( select 1 from TableB where TableA.acctno = TableB.acctno ) ) update t1 set t1.Id = t2.Id, t1.Acctno = t2.Acctno from cte t1 join cte2 t2 on t1.rn = t2.rn where t1.Id is null;
答案 1 :(得分:0)
基于加入更新...您还可以在ACCTNO中忽略null 以获得更好的效果......
update B
set B.ID=A.ID
from TableB as B
join TableA as A
on A.ACCTNO = B.ACCTNO
where B.ACCTNO is not null;
答案 2 :(得分:0)
使用此查询: -
update t2
set t2.id=t1.id
from tableB t2
inner join tableA t1
on t2.acctno=t1.acctno
答案 3 :(得分:0)
您需要将此查询运行到所需的输出
update b set b.ID = a.ID
from TableB as b
left join TableA as a ON a.ACCTNO = b.ACCTNO
where b.ACCTNO IS NOT null;
和
WITH CTE
AS (SELECT T1.ID AS TABLEA_ID,
T1.ACCTNO AS TABLEA_ACCID,
T2.ID AS TABLEB_ID,
T2.ACCTNO AS TANLEB_ACCID
FROM TableA T1
INNER JOIN TableB T2
ON T1.ACCTNO= T2.ACCTNO)
UPDATE CTE
SET TABLEA_ID= TABLEB_ID
答案 4 :(得分:0)
带有CTE
{{1}}
希望它的工作!!
快乐编码!!
答案 5 :(得分:0)
以下SQL将使用表A中ID与acctno匹配的ID填充表B.
UPDATE table_b
SET ID=table_a.id
FROM table_b
INNER JOIN table_a on table_b.acctno=table_a.acctno