计算分类帐查询中特定帐户的余额?

时间:2018-12-21 16:27:11

标签: ms-access

我正在尝试编写我的第一个数据库。

我的问题是计算单个帐户每一行的帐户余额。我尝试过DSUM,但每次都搞砸了。

该表同时包含应付金额付款的两列。

在查询中,我想要一个新列Balance,该列将显示每行帐户AmountDueAmountPaid累计差异。

我知道基本的SQL,但我不是高级用户。

我尝试DSUM()来计算金额总和,但它显示的是所有行的总和,而不是针对每一行。

我的桌子是CreditorTransactionsT

  • TransIDTranaDateCustomerAccountAmountDueAmountPaid

新查询如下:

  • TransIDTranaDateCustomerAccountAmountDueAmountPaidBalance

2 个答案:

答案 0 :(得分:0)

尝试在查询中使用计算所得的字段,它可以进行简单的求和,如果您不想将结果保留在查询之外,则非常理想:

https://www.fontstuff.com/access/acctut02.htm

类似的东西:

余额:[AueDue]-[AmountPaid]

答案 1 :(得分:0)

如果您的表格如下所示:

| TransID | TranaDate  | CustomerAccount | AmountDue | AmountPaid |
|---------|------------|-----------------|-----------|------------|
| 1       | 01/12/2018 | ABC             | £15.00    | £10.00     |
| 2       | 01/12/2018 | DEF             | £20.00    | £5.00      |
| 3       | 02/12/2018 | DEF             | £30.00    | £10.00     |
| 4       | 02/12/2018 | ABC             | £50.00    | £5.00      |
| 5       | 03/12/2018 | ABC             | £10.00    | £15.00     |
| 6       | 04/12/2018 | ABC             | £5.00     | £10.00     | 

然后此SQL:

SELECT  T2.TransID
        , T2.TranaDate
        , T2.CustomerAccount
        , T2.AmountDue
        , T2.AmountPaid
        , SUM(T1.AmountDue) AS TotalDue
        , SUM(T1.AmountPaid) AS TotalPaid
        , SUM(T1.AmountDue) - SUM(T1.AmountPaid) AS Balance
FROM    CreditorTransactionsT T1 INNER JOIN CreditorTransactionsT T2 ON T1.TransID <= T2.TransID AND
                                                                        T1.CustomerAccount = T2.CustomerAccount
GROUP BY T2.TransID
        , T2.TranaDate
        , T2.CustomerAccount
        , T2.AmountPaid
        , T2.AmountDue 
ORDER BY    T2.CustomerAccount, T2.TranaDate  

将返回此表:

| TransID | TranaDate  | CustomerAccount | AmountDue | AmountPaid | TotalDue | TotalPaid | Balance |
|---------|------------|-----------------|-----------|------------|----------|-----------|---------|
| 1       | 01/12/2018 | ABC             | £15.00    | £10.00     | £15.00   | £10.00    | £5.00   |
| 4       | 02/12/2018 | ABC             | £50.00    | £5.00      | £65.00   | £15.00    | £50.00  |
| 5       | 03/12/2018 | ABC             | £10.00    | £15.00     | £75.00   | £30.00    | £45.00  |
| 6       | 04/12/2018 | ABC             | £5.00     | £10.00     | £80.00   | £40.00    | £40.00  |
| 2       | 01/12/2018 | DEF             | £20.00    | £5.00      | £20.00   | £5.00     | £15.00  |
| 3       | 02/12/2018 | DEF             | £30.00    | £10.00     | £50.00   | £15.00    | £35.00  |