SQL SUM GROUP BY two tables

前端 未结 2 1541
無奈伤痛
無奈伤痛 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)

提交回复
热议问题