SQL SUM GROUP BY two tables

前端 未结 2 1524
無奈伤痛
無奈伤痛 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:11

    Are you looking how to join tables and sum using group by?

    First query;

    UPDATE: I think your Account table has 1:many relationship with Transaction table, so, you should get the sum from transaction table and then join with Account. Ideally, you need a left join as below.

    select a.account_no, 
           a.balance, 
           isnull(x.amount,0) amount, 
           (a.balance + isnull(x.amount,0)) correctAmount
    from account a left join (
               select t.account_no, sum(t.amount) amount
               from transactions t
               group by t.account_no ) x
       on a.account_no = x.account_no
    

    SQL-FIDDLE-DEMO (thanks @Josien for tables and data)

    0 讨论(0)
  • 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;
    
    0 讨论(0)
提交回复
热议问题