MySQL从两个表中加入两个表和Sum

时间:2017-02-08 10:40:20

标签: mysql sql join inner-join

我有两张桌子和一张桌子。需要从两个表的列的总和,我尝试但不能得到结果

表-1交付:

表 - 收藏: enter image description here

我的内部联接查询是:

public static int getIndex(int x, String y, String[]v){
    for(int m = 0; m < v.length; m++){
        if (v[m].equalsIgnoreCase(y)){
            x = m;
        }
    }
    return x;
}

结果是: enter image description here 你可以从表二中看出它的总和。我怎样才能得到结果

enter image description here

感谢。

1 个答案:

答案 0 :(得分:1)

首先聚合,然后加入。我想你想加入del_date = coll_date。这是完整的查询:

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;