2

我有四张桌子person,loan,ca,payments

我想获得所有付款金额和现金垫款金额的总和,这些金额与从特定日期加入的人的贷款具有相同的 ID。

这是我的代码,但总和计算不正确:

SELECT pd.*,
    l.total_loan_amount,
    sum(c.ca_total_amount) AS ctot,
    sum(p.payment_amount)
FROM personal_data pd
LEFT JOIN loans l
    ON pd.id_personal_data = l.id_personal_data
LEFT JOIN ca c
    ON l.id_loan = c.id_loan
LEFT JOIN payments p
    ON l.id_loan = p.id_loan
WHERE l.loan_date = curDate()
    AND (
        c.ca_date = curDate()
        OR c.ca_date IS NULL
        )
    AND (
        p.payment_date = curDate()
        OR p.payment_date IS NULL
        )
GROUP BY pd.id_personal_data
4

1 回答 1

2

这样做有时可能会检索到无效结果,因为id有时可能会或可能不会出现在其他表上。

尝试对要检索的每一列使用子查询。

SELECT  pd.*,
        l.total_loan_amount,
        c.totalCA,
        p.totalPayment
FROM    personal_data pd
        LEFT JOIN loans l
            ON pd.id_personal_data = l.id_personal_data
        LEFT JOIN
        (
            SELECT  id_loan, SUM(ca_total_amount) totalCA
            FROM    ca 
        --  WHERE   DATE(ca_date) = DATE(CURDATE()) OR
        --          ca_date IS NULL
            GROUP BY id_loan
        ) c ON l.id_loan = c.id_loan
        LEFT JOIN
        (
            SELECT  id_loan, SUM(payment_amount) totalPayment
            FROM    payments 
        --  WHERE   DATE(payment_date) = DATE(CURDATE()) OR
        --          payment_date IS NULL
            GROUP BY id_loan
        ) p ON l.id_loan = p.id_loan
WHERE DATE(l.loan_date) = DATE(curDate())

我认为dates每次付款和预付现金都无关紧要,因为您正在根据date of loan

于 2012-09-12T02:22:52.660 回答