I have two tables - Table Records with columns ID, Code,ProviderId Table Codes with columns Code, Number, ProviderId
Sample Data:
Table Records
ID Code ProviderId
1 ABC 1
2 DEF 2
3 XYZ 1
4 PQR 2
Table Codes
Code Number ProviderId
ABC 1111 1
Default 9999 1
XYZ 2222 2
Default 4444 2
All the rows in Records table will have a code. Codes table will have a set of codes defined with other information. It is not necessary that all the codes in Records table will have an entry in Codes table. For Code in Records table if corresponding value exists then select the same else need to select Default code based on the ProviderID column.
My expected result is:
ID Code Number
-------------------------
1 ABC 1111
2 DEF 9999 -> Picked up the default for ProviderId 1
3 XYZ 2222
4 PQR 4444 -. Picked up the default for ProviderId 2
I was able to achieve this using left outer join to add the records into a table variable and then again performing an inner join. I was wondering if I can achieve this in a single select.