Lets say I have 2 tables - Table 1 and Table 2:
I want to be able to go down the in the order that the two tables are presented in and match without duplication. So for this example:
- Look at Table 1, ID 1 and match to first type match with Table 2. In this case, Type in Table 1 for ID 1 is A. So in Table 2 look through in the order that it is presented, and get the first color that has type A that hasn't already been matched. In this case that would be "red"
- Look at Table 1, ID 2 and match to first type match with Table 2. In this case, Type in Table 1 for ID 2 is B. So in Table 2 look through in the order that it is presented, and get the first color that has type B that hasn't already been matched. In this case that would be "green"
- Look at Table 1, ID 3 and match to first type match with Table 2. In this case, Type in Table 1 for ID 3 is A again. So in Table 2 look through in the order that it is presented, and get the first color that has type A that hasn't already been matched. In this case that would be "yellow"
- Look at Table 1, ID 4 and match to first type match with Table 2. In this case, Type in Table 1 for ID 4 is C. So in Table 2 look through in the order that it is presented, and get the first color that has type C that hasn't already been matched. In this case that would be "blue"
- Look at Table 1, ID 5 and match to first type match with Table 2. In this case, Type in Table 1 for ID 5 is B again. So in Table 2 look through in the order that it is presented, and get the first color that has type B that hasn't already been matched. In this case all Type Bs have already been matched, so return "Null"
So the results table would look something like this:
How would one do this is SQL? Is there a type of "JOIN" that would do this? Is it possible to have for-loops in SQL where you find the match from Table 2 and remove that instance from Table 2 in time for the next iteration of the loop?


