sum from both mysql table columns

I have two mysql tables:

table: loan
--------------------------------------------------------
 id | advance_id | loan_amount | deposit_amount | date
--------------------------------------------------------
 1 | 22556678 | 5000 | 0 | 2015-02-06
 2 | 22556678 | 5000 | 0 | 2015-02-07
--------------------------------------------------------

table: advance
--------------------------------------------------------
id | advance_id | advance_amount | purpose | date
--------------------------------------------------------
 1 | 22556678 | 20000 | purchase | 2015-01-30
 2 | 22556678 | 10000 | purchase | 2015-01-31

I want to get sum of 'loan_amount' from table: loan and sum of 'advance_amount' from table: advance in one mysql query joined by INNER JOIN.

How to get the sum from columns of two tables?

SELECT 
  a.advance_id,
  SUM(a.advance_amount) AS adv_amount,
  a.purpose,
  a.date,
  SUM(l.loan_amount) AS loan_amount 
FROM
  advance AS a 
  INNER JOIN loan AS l 
    ON a.advance_id = l.advance_id 
GROUP BY a.advance_id 
HAVING SUM(l.loan_amount) - SUM(l.deposit_amount) > 0 

Upvotes: 1

Views: 105

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

you can rewrite your query as

SELECT 
  a.advance_id,
  SUM(a.advance_amount) AS adv_amount,
  a.purpose,
  a.date,
  l.loan_amount 
FROM
  advance AS a 
  INNER JOIN 
  (
    SELECT advance_id,SUM(deposit_amount) AS loan_amount
    FROM loan
    GROUP BY advance_id
    HAVING SUM(loan_amount) - SUM(deposit_amount) > 0 
  )  AS l USING(advance_id)
GROUP BY a.advance_id 

DEMO

Upvotes: 2

Related Questions