Domanda

Here is the screnario, i have2 tables table1 and table2 and i need to update the table1 using table2 as there are quite a few duplicate in table2 but need to pick one using the where clause in table2

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

Now i need to get the distinct values from Table2 where the source is SS and need to be mapped against the Table1 email.

I'm using something like this but is not working,

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')

any help would be a helpful

È stato utile?

Soluzione

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

If there is more than one matching PP value in Table2, you have to a choice. The above example picks the maximum. If that's not what you're looking for, please clarify your question.

Altri suggerimenti

For this type of update, you can use the from clause. What you want to do is select a single row for each email address where the source is "SS". The following chooses a randome row using row_number() and newid():

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top