SQL SUM GROUP BY two tables

前端 未结 2 1525
無奈伤痛
無奈伤痛 2021-01-01 02:37

I\'m having difficulty writing an SQL query that will correctly group account_no together and subtracting an amount.

Firstly I wrote this query which updates everyth

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 03:13

    For your query, to get the two rows grouped on one row, you can try grouping on the account number AND the balance:

    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;
    

    (By the way, I've used the ANSI join instead of the 'old' way of joining tables, because it's much more clear what you're doing that way.)

    EDIT

    To make things a bit more clear, I've made a SQL Fiddle. Does this represent your situation more or less correctly?

    EDIT2

    The above query would not show any accounts without transactions, as Kaf commented. That might be what you want, but in case it's not you can switch the join tables like this:

    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;
    

提交回复
热议问题