I have two tables: Accounts and Transactions. I would like to join them to have an output table as per below:
Accounts Table:
| AccountID | AccounNumber |
|---|---|
| Acc1 | 000000001 |
| Acc2 | 000000002 |
| Acc3 | 000000003 |
Transactions Table:
| TransactionID | FromAccount | ToAccount |
|---|---|---|
| Tr1 | Acc1 | Acc2 |
| Tr2 | Acc2 | Acc3 |
Output:
| TransactionID | FromAccount | ToAccount |
|---|---|---|
| Tr1 | 000000001 | 000000002 |
| Tr2 | 000000002 | 000000003 |
CodePudding user response:
You need to JOIN with Accounts table two times to get your expected result.
The query will be:
SELECT TR.TransactionID,
A1.AccounNumber AS FromAccount,
A2.AccounNumber AS ToAccount,
FROM Transactions TR
INNER JOIN Accounts A1 ON A1.AccountID = TR.FromAccount
INNER JOIN Accounts A2 ON A2.AccountID = TR.ToAccount
