我有3个表,如图所示:
每个表中的测试数据如下:
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
我想在一个查询中获取FromAccID和ToAccID的帐户名称及其组名,如下所示:
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
请帮助我实现这一目标。
答案 0 :(得分:3)
您可以在一个查询中多次使用同一个表,只需使用别名。
像
这样的东西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