通过访问加入多个表

时间:2016-07-13 08:46:23

标签: ms-access join

我在Access数据库中有三个表。 CheckDJCashDJ的列数多于CashRJ。我想将这些表合并为一个。我有以下查询:

SELECT
    a.acctname,
    a.code,
    (
        sum(a.debit) + sum(b.debit) + sum(c.debit)
    ) AS DebitTotal,
    (
        sum(a.credit) + sum(b.credit) + sum(c.credit)
    ) AS CreditTotal
FROM
    (
        CheckDJ a
        LEFT OUTER JOIN CashRJ b ON a.id = b.id
    )
LEFT OUTER JOIN CashDJ c ON a.id = c.id
GROUP BY
    a.acctname,
    a.code

问题是,上面的代码只显示CheckDJ的类似数据。谁能帮我?提前谢谢!

2 个答案:

答案 0 :(得分:0)

我明白你的意思,你不应该使用群组功能。即:

sum(a.credit) + sum(b.credit) + sum(c.credit)

sum(a.debit) + sum(b.debit) + sum(c.debit)

有了这个,你将获得相同数量的每条记录。只需将它们添加到一起,无需任何组功能。

答案 1 :(得分:0)

假设acctnamecode是主键,请从UNION查询中选择以包含所有记录:

SELECT acctname, code, SUM(debit) As DebitTotal, SUM(credit) AS CreditTotal
FROM
(
    SELECT acctname, code, debit, credit, "CheckDJ" As SoursTblName 
    FROM CheckDJ 
    Union
    SELECT acctname, code, debit, credit, "CashRJ" As SoursTblName 
    FROM CashRJ 
    Union
    SELECT acctname, code, debit, credit, "CashDJ" As SoursTblName 
    FROM CashDJ 
)
GROUP BY acctname, code

添加了字段SoursTblName,以防止将来自不同表的相同记录合并为一个。

如果CheckDJCashDJCashRJ中可能包含相同的记录,请使用此查询:

SELECT acctname, code, SUM(debitSum) As DebitTotal, SUM(creditSum) AS CreditTotal
FROM
(
    SELECT acctname, code, SUM(debit) As debitSum, SUM(credit) As creditSum, "CheckDJ" As SoursTblName 
    FROM CheckDJ 
    GROUP BY acctname, code
    Union
    SELECT acctname, code, SUM(debit) As debitSum, SUM(credit) As creditSum,  "CashRJ" As SoursTblName 
    FROM CashRJ 
    GROUP BY acctname, code
    Union
    SELECT acctname, code, SUM(debit) As debitSum, SUM(credit) As creditSum,  "CashDJ" As SoursTblName 
    FROM CashDJ 
    GROUP BY acctname, code
)
GROUP BY acctname, code