1

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.

3
  • 3
    That GROUP BY is invalid, will return an unpredictable result in older MySQL versions, will raise an error in new versions (unless in compatibility mode.) The general GROUP BY rule says: If a GROUP BY clause is specified, each column reference in the SELECT list must either identify a grouping column or be the argument of a set function! Commented Feb 8, 2017 at 10:43
  • 2
    I don't see an ON clause in your query. Commented Feb 8, 2017 at 10:47
  • can you explain your question it is bit confusing Commented Feb 8, 2017 at 11:09

1 Answer 1

1

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.