sadi
sadi

Reputation: 61

MySQL Join Two Tables and Sum from both Table

I have two table & Need sum of column from both table, i try but cant get result

table-1 Delivery:

Table- Collection: enter image description here

My inner join query was:

SELECT loan_collection.coll_date,
       sum(loan_collection.coloan_amo) AS coloan_amo,
       sum(loan_collection.sc_coll) AS sc_coll,
       sum(loan_collection.total_coll) AS total_coll,
       loan_collection.year,
       bag_del_rentcoll.rent_bagdel,
       bag_del_rentcoll.rent_amo,
       bag_del_rentcoll.booking,
       bag_del_rentcoll.rent_rece
FROM loan_collection AS loan_collection
INNER JOIN
  (SELECT del_date,
          sum(rent_bagdel) AS rent_bagdel,
          sum(rent_amo) AS rent_amo,
          sum(booking) AS booking,
          sum(rent_rece) AS rent_rece
   FROM bag_del_rentcoll) AS bag_del_rentcoll
GROUP BY loan_collection.coll_date

The result is: enter image description here as you can see it's sum of all from table two. How can i get result as

enter image description here

Thanks.

Upvotes: 1

Views: 1178

Answers (1)

Thorsten Kettner
Thorsten Kettner

Reputation: 95100

Aggregate first, then join. I suppose you want to join on del_date = coll_date. Here is the complete query:

SELECT 
  lc.coll_date,
  lc.sum_coloan_amo,
  lc.sum_sc_coll,
  lc.sum_total_coll,
  lc.max_year,
  bdr.sum_rent_bagdel,
  bdr.sum_rent_amo,
  bdr.sum_booking,
  bdr.sum_rent_rece 
FROM 
(
  SELECT
    coll_date,
    SUM(coloan_amo) AS sum_coloan_amo
    SUM(sc_coll) AS sum_sc_coll,
    SUM(total_coll) AS sum_total_coll,
    MAX(year) AS max_year
  FROM loan_collection
  GROUP BY coll_date
) lc
INNER JOIN
(
  SELECT 
    del_date,
    sum(rent_bagdel) AS sum_rent_bagdel,
    sum(rent_amo) AS sum_rent_amo,
    sum(booking) AS sum_booking,
    sum(rent_rece) AS sum_rent_rece
  FROM bag_del_rentcoll
  GROUP BY del_date
) bdr ON bdr.del_date = lc.coll_date;

Upvotes: 1

Related Questions