Hello All.
I'm trying to create a Microsoft Query on Excel that connects to an external database and was having a SQL question on how to return query records based on information below.
Although it's in excel, I believe this is more of a general SQL question. I apologize and thank you for the long read in advance!
Below are 2 Table structures that only include fields that are relevant to this question.
*==========*
| Transaction |
*==========*
TransactionID (Unique)
EntityID
ForEntityID
*=======*
| Entity |
*=======*
EntityID (Unique)
Name
Using the example table structures from above, I currently have a microsoft query which returns all records from [Transaction] Table and also join the [Entity] Table by (Entity.EntityID = Transaction.EntityID) so that it returns on record row the name of the Entity as one of the columns.
I am having trouble understanding how I may be able to achieve the next task.
The values of 'Transaction.EntityID' and 'Transaction.ForEntityID' are both consisting of the IDs that match the Unique ID of 'Entity.EntityID'.
While most records in [Transaction] Table have empty values for 'Transaction.ForEntityID', Some records do contain values in both 'EntityID' and 'ForEntityID'
For those records in [Transaction] where there is value in 'Transaction.ForEntityID', I want to append another column in the query that shows the name of the entity that the record is being entered "For" (the value in 'Entity.Name').
The problem however, is that I already have a join on (Entity.EntityID = Transaction.EntityID). It wouldn't be logically possible to add another join (Entity.EntityID = Transaction.ForEntityID) is this correct?
Simply put, what I'm hoping to achieve is:
If there's a value in 'Transaction.ForEntityID', I want to append a column in the query that returns the matching value from Entity Table (Entity.EntityID = Transaction.ForEntityID) but if there is no value in 'Transaction.ForEntityID', I'd like that query column to return the matching value from Entity Table (Entity.EntityID = Transaction.EntityID)
For Example:
*=================*
| Transaction Records |
*=================*
TransactionID - EntityID - ForEntityID
100 - 1 - (blank)
101 - 1 - 2
102 - 2 - (blank)
*============*
| Entity Records |
*============*
EntityID - Name
1 - Albert
2 - Brian
On the query, How can it be structured so that the query record are returned as follows :
ID: 100, EntityID: 1, ForEntityID: , EntityName: Albert
ID: 101, EntityID: 1, ForEntityID: 2, EntityName: Brian
ID: 102, EntityID: 2, ForEntityID: , EntityName: Brian
I'm sorry for not the most efficient way of asking the question due to my limited knowledge in this matter. Hope you understand, and I appreciate any help!
Bookmarks