我正在尝试进行2次LEFT JOINS,SUM结果,减去另一次的总和。一个是正确求和,但是当我放两个连接时,其中一个连接不正确。
SELECT
j.jobNumber, j.customerID, j.costDelivery, j.costCallout, j.costLabour ,
c.customerID, c.firstName, c.lastName ,
IFNULL(sum(jp.amount),0) AS Total_Paid ,
IFNULL(j.costDelivery,0) + IFNULL(j.costCallout,0) + IFNULL(j.costLabour,0) + IFNULL(sum(p.unitPrice*p.quantity),0) AS Total_Cost
FROM s_jobcards AS j
INNER JOIN s_customers AS c ON j.customerID = c.customerID
LEFT OUTER JOIN s_payments AS jp ON j.jobNumber = jp.jobNumber
LEFT OUTER JOIN s_partOrders AS p ON j.jobNumber = p.jobNumber
GROUP BY j.jobNumber
HAVING Total_Cost > Total_Paid
Total_Paid
列说明jp.amount
的总和不正确。但是,Total_Cost
正确相加。有什么想法吗?
答案 0 :(得分:1)
试试这个:
SELECT j.jobNumber, j.customerID, j.costDelivery, j.costCallout, j.costLabour,
c.customerID, c.firstName, c.lastName, IFNULL(jp.payment, 0) AS Total_Paid ,
(IFNULL(j.costDelivery, 0) + IFNULL(j.costCallout, 0) + IFNULL(j.costLabour, 0) + IFNULL(p.cost, 0)) AS Total_Cost
FROM s_jobcards AS j
INNER JOIN s_customers AS c ON j.customerID = c.customerID
LEFT OUTER JOIN (SELECT jp.jobNumber, SUM(jp.amount) payment
FROM s_payments AS jp
GROUP BY jp.jobNumber
) AS jp ON j.jobNumber = jp.jobNumber
LEFT OUTER JOIN (SELECT p.jobNumber, SUM(p.unitPrice * p.quantity) cost
FROM s_partOrders AS p
GROUP BY p.jobNumber
) AS p ON j.jobNumber = p.jobNumber
GROUP BY j.jobNumber
HAVING Total_Cost > Total_Paid;