2015-04-22 127 views
1

我在sqlite中有兩個單獨的表,稱爲發票和購買,我使用下面的查詢來檢索與項目7相關的所有發票和購買總和。事情是發票有三條記錄和sql中返回的值是正確的,但購買等價物是錯誤的,因爲只有一條記錄,但返回值乘以三。來自兩個表的sql總數

SELECT sum(invoice.invoice_net) As Sales, sum(purchase.total_order) As Purchases 
FROM invoice 
LEFT JOIN purchase 
ON purchase.projectID=invoice.projectID 
WHERE invoice.projectID=7 

如何加入這兩條語句,以便正確返回數據。我個人知道他們工作得很好。我試過聯盟,但是把數據放在一列中。

SELECT sum(invoice.invoice_net) As Sales 
FROM invoice 
WHERE projectID=7 

SELECT sum(purchase.order_total) As Purchases 
FROM purchase 
WHERE projectID=7 

回答

1

一種選擇是sum使用子查詢的結果,然後執行outer join

SELECT invoice.Sales, purchase.Purchases 
FROM (
    SELECT sum(invoice.invoice_net) As Sales, projectID 
    FROM invoice 
    GROUP BY projectID 
) invoice LEFT JOIN (
    SELECT sum(total_order) As Purchases, projectID 
    FROM purchase 
    GROUP BY projectID 
) purchase ON purchase.projectID=invoice.projectID 
WHERE invoice.projectID=7 

另一種選擇是使用一個相關子查詢:

SELECT sum(i.invoice_net) As Sales, 
    (SELECT sum(p.total_order) 
    FROM purchase p 
    WHERE p.projectID = i.projectID) As Purchases 
FROM invoice i 
WHERE i.projectID=7