用计数和总和连接表

时间:2018-04-03 05:49:50

标签: mysql sql

我有两张桌子 loanform和schedule_loanform loanform enter image description here

我需要MySQL查询但无法帮助我解决它吗?

2 个答案:

答案 0 :(得分:1)

你可以试试这个。

使用两个子查询2和JOIN Zone

您的Due_Date格式为dd-mm-yyyy,因此需要使用STR_TO_DATE转换日期。获取条件之间的日期。

SELECT TotalZoneCase,Region,T.Zone,LoanAmount,MarkUp
FROM 
(
    SELECT Zone,SUM(LoanAmount) AS LoanAmount,COUNT(1) as TotalZoneCase
    FROM loanform
    GROUP BY Zone
) AS T
INNER JOIN 
(
    SELECT l.Zone,l.Region,SUM(MarkUp)  MarkUp
    FROM loanform l 
    INNER JOIN schedule_loanform s on l.App_ID = s.App_ID
    WHERE  STR_TO_DATE(Due_Date, '%d-%m-%Y') >= STR_TO_DATE('01-01-2018', '%d-%m-%Y') and  STR_TO_DATE(Due_Date, '%d-%m-%Y')<=STR_TO_DATE('31-06-2018', '%d-%m-%Y')
    GROUP BY l.Zone,l.Region
) T2 ON T.Zone = T2.Zone

SQLFiddle

答案 1 :(得分:1)

  

根据您的要求,只需尝试此

即可
SELECT COUNT(lf.Zone) AS TotalZoneCase, lf.Region, lf.Zone, SUM(lf.LoanAmount),
SUM(sl.MarkUp) FROM loanform lf
INNER JOIN schedule_loanform sl ON lf.App_ID = sl.App_ID
WHERE '2018-01-01' >= DATE(Disburse_Date) <= '2018-06-30'
GROUP BY Region, Zone ORDER BY lf.App_ID;