2012-09-28 84 views
1

下面是實際發票表加入兩個MySQL結果集使用左外連接

enter image description here

分組它的基礎上invoiceID後,ResultSet是 enter image description here

至實際付款表

enter image description here

及其付款結果分組基於invoiceID後t是

enter image description here

現在我想加入這兩個結果[付款和發票表],並找到了平衡量基於InvoiceID和非匹配金額減去總記錄的餘額列應該是零。我試過這個,但沒有得到預期的結果。

+0

我並不完全相信你想是什麼。 – ajon

回答

1

嘗試這樣的事情,

SELECT a.InvoiceID, 
     a.totalSum InvoiceAmount, 
     b.totalSum PaymentAmount, 
     a.totalSum - COALESCE(b.totalSum, 0) TotalBalance 
FROM 
    (
     SELECT InvoiceID, SUM(Total) totalSum 
     FROM InvoiceTB 
     GROUP BY InvoiceID 
    ) a LEFT JOIN 
    (
     SELECT InvoiceID, SUM(Total) totalSum 
     FROM paymentTB 
     GROUP BY InvoiceID 
    ) b 
     ON a.InvoiceID = b.InvoiceID 
+0

@Uma yuo're歡迎! –