连接两个表并使用 MySQL 连接对列求和

Join two tables and summing over the columns using MySQL joins

对不起,如果我又问了这个问题。我已经尝试了所有可能的解决方案,但没有想出解决方案。 我还在此处附加了一个 sqlfiddle link to the problem 来复制问题。

我有两个 table:合同和 Contracts_balance

对于每个 table 我正在编写查询: 对于合同,使用此查询总结 ord_qty 列并按(product_name、pack_size 和 startr_date)分组:

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  

输出如下所示:

table contracts

对于 contracts_balance,使用此查询对 balance_aftermonths 列求和并按(product_name、pack_size 和 startr_date)分组:

  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   ;  

输出如下所示: table contracts_balance

我正在尝试合并这两个查询,因此输出如下所示:

desired output

我的问题解决方法: 如 sqlfddle 中所写,我正在使用 join 对列求和,但它显示错误的结果

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  

在与contractid的连接条件中添加product_name和pack_size以获得预期结果。

-- 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  ;

请检查这个urlhttp://sqlfiddle.com/#!9/f1cef6/97