Search code examples
mysqljoinsubqueryuniondistinct

Join two tables and summing over the columns using MySQL joins


I am sorry if I have asked this question again. I have tried every possible solution and didn't come up with a solution. I am also attaching a sqlfiddle here link to the problemto replicate the problem.

I have two tables: Contracts and Contracts_balance

For each table I am writing the query: For contracts, to sum up the ord_qty colum and grouping by (product_name, pack_size and startr_date)using this query:

SELECT  c.contract_id, c.product_name, c.pack_size, sum(c.qty), c.contract_prod, c.end_date,c.start_date
From contracts c
GROUP BY c.product_name,c.start_Date , c.pack_size  

The output looks like this:

table contracts

For contracts_balance, to sum the balance_aftermonths column and grouping by (product_name, pack_size and startr_date) using this query:

  SELECT cb.contract_id_fk, cb.product_name, cb.pack_size, cb.monthlydates , SUM(cb.balance_aftermonth) as mysum
            FROM contracts_balance cb
           WHERE MONTH(cb.monthlydates) = 3
     GROUP BY cb.product_name, cb.start_Date , cb.pack_size   ;  

The output looks like this: table contracts_balance

I am trying to combine these two queries so the output looks like this:

desired output

MY Approach to the problem: as written inside the sqlfddle , I am using join to sum the columns but it shows me wrong results

SELECT  c.contract_id, c.product_name, c.pack_size, sum(c.qty), c.contract_prod, c.end_date,c.start_date, test.mysum,test.monthlydates
From contracts c
JOIN
( SELECT cb.contract_id_fk, cb.product_name, cb.pack_size, cb.member, cb.monthlydates , SUM(cb.balance_aftermonth) as mysum
            FROM contracts_balance cb
           WHERE MONTH(cb.monthlydates) = 3
     GROUP BY cb.product_name, cb.start_Date , cb.pack_size     

          ) test on (test.contract_id_fk = c.contract_id)
          
GROUP BY c.product_name,c.start_Date , c.pack_size  

Solution

  • Add product_name and pack_size in joining condition with contractid for getting expected result.

    -- MySQL (v5.6)
    SELECT  c.contract_id, c.product_name, c.pack_size, sum(c.qty), c.contract_prod, c.end_date,c.start_date, test.mysum,test.monthlydates
    From contracts c
    JOIN
    ( SELECT cb.contract_id_fk, cb.product_name, cb.pack_size, cb.member, cb.monthlydates , SUM(cb.balance_aftermonth) as mysum
                FROM contracts_balance cb
               WHERE MONTH(cb.monthlydates) = 3
         GROUP BY cb.product_name, cb.start_Date , cb.pack_size     
    
              ) test on (test.contract_id_fk = c.contract_id
                        AND c.product_name = test.product_name
                        AND c.pack_size = test.pack_size)
              
    GROUP BY c.product_name,c.start_Date , c.pack_size  ;
    

    Please check this url http://sqlfiddle.com/#!9/f1cef6/97