Problem Statement: I have a table that holds three pieces of information (Number, Id, Type). Let’s call it table A:
╔══════╦════╦══════╗
║Number║ Id ║Type ║
╠══════╬════╬══════╣
║ 1234 ║1111║Test 1║
║ 1234 ║2222║Test 1║
║ 1234 ║3333║Test 2║
║ 1234 ║4444║Test 2║
╚══════╩════╩══════╝
I have another table that holds 4 pieces of information (Number, Test1, Test2, ID). Let’s call it table B:
╔══════╦═════╦══════╦══════════════════╗
║Number║Test1║Test 2║ ID ║
╠══════╬═════╬══════╬══════════════════╣
║ 1234 ║1111 ║ ║a1v1b0000006lmMAAQ║
║ 1234 ║2222 ║ ║a1v1b0000006lmNAAQ║
║ 1234 ║ ║3333 ║a1vf1000000qvTYAAY║
║ 1234 ║ ║4444 ║a1vf1000000qvTiAAI║
╚══════╩═════╩══════╩══════════════════╝
What I would like to do is, based on Number and Type from Table A, to search the Table B and return the corresponding ID.
The desired outcome is as follows:
╔══════╦════╦══════╦══════════════════╗
║Number║ ID ║Type ║ ID ║
╠══════╬════╬══════╬══════════════════╣
║ 1234 ║1111║Test 1║a1v1b0000006lmMAAQ║
║ 1234 ║2222║Test 1║a1v1b0000006lmNAAQ║
║ 1234 ║3333║Test 2║a1vf1000000qvTYAAY║
║ 1234 ║4444║Test 2║a1vf1000000qvTiAAI║
╚══════╩════╩══════╩══════════════════╝
NB: I have tried to use a decode but reading up on it, I am getting mixed signals whether this is the correct approach.
Best Answer
This is a quick solution that uses
union all
.The first query finds the matching rows between
Table1
andTable2
whereTable1.Type
= 'Test 1' andTable1.Id
=Table2.[Test 1]
The second query finds the matching rows between
Table1
andTable2
whereTable1.Type
= 'Test 2' andTable1.Id
=Table2.[Test 2]