Nagesh
Nagesh

Reputation: 1308

SQL Query to join two columns of a table with other tables

I have 3 tables as shown in the diagram: Table Design

The test data in each of these tables is as given below:

ACCOUNT_GROUP

     GroupID    Name
     101    Bank Accounts
     105    Cash-in-hand
     113    Indirect Expenses
     120    Purchase Accounts
     122    Sales Accounts
     125    Sundry Creditors

ACCOUNT_MASTER

AccID   Name          GroupID
1001    RBS A/C 23456   101
1002    HSBC A/C 123456 101
1003    CASH A/C        105
1004    DISCOUNT        113
1005    CASH SALES      122
1006    CASH PURCHASE   120
1007    JOHNSON         125

ACCOUNT_TXNS

TxnID   TxnDate  FromAccID  ToAccID Amt CrDr
1   20-Jul-2011 1002    1003    250000  C
2   20-Jul-2011 1001    1002    985241  C
3   20-Jul-2011 1005    1003    65451   C
4   20-Jul-2011 1006    1003    412874  D
5   20-Jul-2011 1007    1003    521400  C
6   20-Jul-2011 1003    1007    200     D

I want to get the account names of both FromAccID and ToAccID and their group names in a single query like this:

TxnID   TxnDate FromAcc         FromAccGroup      ToAcc            ToAccountGroup    Amt    CrDr
1   20-Jul-2011 HSBC A/C 123456 Bank Accounts     CASH A/C          Cash-in-hand     250000 C
2   20-Jul-2011 RBS A/C 23456   Bank Accounts     HSBC A/C 123456   Bank Accounts    985241 C
3   20-Jul-2011 CASH SALES      Sales Accounts    CASH A/C          Cash-in-hand     65451  C
4   20-Jul-2011 CASH PURCHASE   Purchase Accounts CASH A/C          Cash-in-hand     412874 D
5   20-Jul-2011 JOHNSON         Sundry Creditors  CASH A/C          Cash-in-hand     521400 C
6   20-Jul-2011 CASH A/C        Cash-in-hand      JOHNSON           Sundry Creditors 200    D

Kindly help me to achieve this.

Upvotes: 0

Views: 528

Answers (1)

Adriaan Stander
Adriaan Stander

Reputation: 166526

You can use the same table more than once in a single query, just use aliases.

Something like

SELECT  *
FROM    ACCOUNT_TXNS txns INNER JOIN
        ACCOUNT_MASTER fromAcc  ON  txns.FromAccID = fromAcc.AccID INNER JOIN
        ACCOUNT_GROUP fromAccGrp    ON  fromAcc.GroupID = fromAccGrp.GroupID INNER JOIN
        ACCOUNT_MASTER toAcc    ON  txns.ToAccID = toAcc.AccID INNER JOIN
        ACCOUNT_GROUP toAccGrp  ON  toAcc.GroupID = toAccGrp.GroupID

Upvotes: 3

Related Questions