Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Author |
Topic |
amits
Starting Member
6 Posts |
Posted - 2010-10-06 : 01:13:28
|
I have a main table to which I need to append the data from two other tables - tableA and tableB. I want to add a new variable to main table that says "match" if it has a match from tableA and "others" if it has a match from tableB. Here is the data:Maintable AcctNo Name123 Jason Smith111 Tom Altar222 Jessica Mo11144 Tracy Smit5421 Jack Brown364 Jack DanielsTableA AcctNo Surname Firstname123 Jason Smith11144 Tracy SmitTableB AcctNo Surname Firstname111 Tom Altar5421 Jack BrownRESULTS SHOULD LOOK SOMETHING LIKE AcctNo Name Surname Firstname Match123 Jason Smith Jason Smith Exact111 Tom Altar Tom Altar Other222 Jessica Mo 11144 Tracy Smit Tracy Smit Exact5421 Jack Brown Jack Brown Other364 Jack Daniels |
|
amits
Starting Member
6 Posts |
Posted - 2010-10-06 : 01:21:01
|
sorry I forgot to mention that I can't use UNION to combine TableA and tableB as in reality there are few different fields in two tables. |
 |
|
kunal.mehta
Yak Posting Veteran
83 Posts |
Posted - 2010-10-06 : 02:04:01
|
declare @Maintable as table( acctno int, name varchar(20))declare @TableA as table( acctno int, Surname varchar(20), firstname varchar(20))declare @Tableb as table( acctno int, Surname varchar(20), firstname varchar(20))insert into @Maintableselect 123, 'Jason Smith'union select 111, 'Tom Altar'union select 222, 'Jessica Mo'union select 11144, 'Tracy Smit'union select 5421, 'Jack Brown'union select 364, 'Jack Daniels'insert into @TableA select 123, 'Jason', 'Smith'union select 11144, 'Tracy', 'Smit'insert into @Tablebselect 111, 'Tom', 'Altar'union select 5421, 'Jack', 'Brown'select temp.acctno,temp.name,COALESCE(asurname,bsurname,'') surname,COALESCE(Afirstname,bfirstname,'') firstname,case COALESCE(A,B,0) when A then 'Exact' when B then 'Other' Else '' end Matchfrom(select m.*,a.acctno A,a.firstname Afirstname,a.Surname asurname,b.acctno B,b.firstname bfirstname,b.Surname bsurname from @Maintable mleft outer join @TableA a on m.acctno = a.acctnoleft outer join @Tableb b on m.acctno = b.acctno) temp |
 |
|
Sachin.Nand
2937 Posts |
Posted - 2010-10-06 : 02:38:47
|
I think there is no need for the derived tableselect m.acctno, m.name, COALESCE(a.surname,b.surname,'') surname, COALESCE(A.firstname,b.firstname,'') firstname, case COALESCE(a.acctno,b.acctno,0) when a.acctno then 'Exact' when b.acctno then 'Other' Else '' end Match from @Maintable mleft outer join @TableA a on m.acctno = a.acctnoleft outer join @Tableb b on m.acctno = b.acctno PBUH |
 |
|
|
|
|
|
|