这是screnario,我有2个表table1和table2,我需要使用table2更新table1,因为table2中有很多重复,但需要使用table2中的where子句选择一个
Table1(unique table)
Email_Address|Country|Region|Source|PP|PS
a@a.com IN AP SS ES PP
b@g.com US AM ES ST PO
Table2(duplicate values)
Email_Address|Country|Region|Source|PP|PS
a@a.com IN AP SS ES PP
a@a.com ES AP SS ES SST
a@a.com IN AP MS ES P
a@a.com IN AP NS ST PP
b@g.com US AM ES ST PO
b@g.com IN AP NS ST PP
现在我需要从Table2获取不同的值,其中源是SS并且需要针对Table1电子邮件进行映射。
我使用过这样的东西但是没有用,
Update Table1
Set Table1.Country=Table2.Country,Table1.PP=Table2.PP
Where Email_Address In (Select Distinct Email_Address
From Table2
where Table2.Source = 'SS')
任何帮助都是有帮助的
答案 0 :(得分:0)
update t1
set Source = 'SS'
, PP = t2.MaxPP
from Table1 t1
join (
select Email_address
, max(PP) as MaxPP -- Pick max PP from the available group
from Table2
where Source = 'SS'
group by
Email_address
) t2
on t2.Email_address = t1.Email_address
如果PP
中有多个匹配的Table2
值,则必须选择。上面的例子选择了最大值。如果那不是你想要的,请澄清你的问题。
答案 1 :(得分:0)
对于此类更新,您可以使用from
子句。您要做的是为源为“SS”的每个电子邮件地址选择一行。以下选项使用row_number()
和newid()
选择一个randome行:
Update t1
Set Source = t2.Source,
PP = t2.PP
from table1 t1 join
(select t2.*,
row_number() over (partition by email_address order by newid()) as seqnum
from table2 t2
where t2.Source = 'SS'
) t2
on t1.email_address = t2.email_address and seqnum = 1;