Access 2003可以查询多个表的结果

时间:2017-07-29 13:59:44

标签: sql ms-access

我是新用户,任何人都可以帮助查询超过1个表格的结果

离。

表Tdeposit

user    amountDeposit
A                5000
A                6000
B                1000
B                3000

表Twithdraw

user    amountWithdraw
A                 2000
A                 3000
B                 1000

(我需要做的结果)

user    current
A          6000 /*edit from 7000* ty for notice*/
B          3000

如何使用设计视图或我需要在sql视图中执行?感谢您的帮助

2 个答案:

答案 0 :(得分:1)

无论您是否在任何表格中都有行,这都会有效。

    select
    USER, SUM(Amount)
    from
    (
    select 
    user, amountDeposit as Amount from TDeposit
    UNION ALL
    SELECT
    user, -amountWithdraw as Amount from TWithdraw
    ) as x
    Group By user
order by user

答案 1 :(得分:0)

为了避免在每个表中使用相同用户的多个实例进行重复计算,请考虑连接聚合派生表,然后在外部查询中获取总和的差异:

SELECT d.[user], (d.[DepositSum] - w.[WDrawSum]) As [current]
FROM
   (SELECT [user], SUM([amountDeposit]) As DepositSum
    FROM Tdeposit
    GROUP BY [user]) As d
INNER JOIN
   (SELECT [user], SUM([amountWithdraw]) As WDrawSum
    FROM Twithdraw
    GROUP BY [user]) As w
 ON d.[user] = w.[user]

或者,您可以将每个派生表另存为单独的已保存的MS Access查询(或视图):

SELECT d.[user], (d.[DepositSum] - w.[WDrawSum]) As [current]
FROM depositAggQ d
INNER JOIN withdrawAgg w
 ON d.[user] = w.[user]