我在编写将正确将account_no分组在一起并减去金额的SQL查询时遇到困难。
首先,我编写了此查询,它更新了所有内容,但ACCOUNT_NO A-102最终应为4500,而不是两个不同的正确余额。
select transactions.account_no, account.balance, transactions.amount, (account.balance + transactions.amount) AS "CORRECT BALANCE" from transactions, account where account.account_no = transactions.account_no; ACCOUNT_NO| BALANCE | AMOUNT | CORRECTBALANCE A-102 | 4000 | 2000 | 6000 A-102 | 4000 | -1500 | 2500 A-222 | 8000 | -1000 | 7000 A-305 | 2000 | 1300 | 3300
我试图对account_no进行求和和分组,但是我无法弄清楚如何对两个表执行此操作。这只是我尝试过的事情,但无法正常工作。
select transactions.account_no, SUM(transactions.amount) from transactions group by transactions.account_no; ACCOUNT_NO| SUM(TRANSACTIONS.AMOUNT) A-305 | 1300 A-102 | 500 A-222 | -1000
预期结果应为:
ACCOUNT_NO| BALANCE | AMOUNT | CORRECTBALANCE A-102 | 4000 | 500 | 4500 A-222 | 8000 | -1000 | 7000 A-305 | 2000 | 1300 | 3300
这是因为帐户A-102有两个不同的金额,但余额相同。
对于您的查询,要将两行分组为一行,可以尝试对帐号和余额进行分组:
SELECT T.account_no ,A.balance ,SUM(T.amount) AS TotalAmount ,(A.balance + SUM(T.amount)) AS "CORRECT BALANCE" FROM transactions AS T INNER JOIN account AS A ON T.account_no = A.account_no GROUP BY T.account_no, A.balance;
(顺便说一句,我使用了ANSI联接,而不是联接表的“旧”方法,因为这样可以更清楚地知道自己在做什么。)
编辑
为了使事情更加清楚,我制作了一个 SQL Fiddle 。这是否或多或少正确地代表了您的情况?
编辑2
正如Kaf所说,以上查询不会显示没有交易的任何帐户。那可能就是您想要的,但是如果不是这样,您可以像这样切换联接表:
SELECT A.account_no ,A.balance ,SUM(T.amount) AS TotalAmount ,(A.balance + SUM(T.amount)) AS "CORRECT BALANCE" FROM account AS A LEFT OUTER JOIN transactions AS T ON T.account_no = A.account_no GROUP BY A.account_no, A.balance;