2011-11-05 133 views
0

表A:qa_invoicesMySQL的左連接複製

invoice_code invoice_date 
    1    25 
    2    25 
    3    26 
    4    27 

表B:qa_invoicesitems

invoice_code item_quantity item_name 
    1    2    Mouse 
    1    1    CPU 
    2    5    Keyboard 
    3    1    Router 
    4    3    Switch 

我的查詢:

SELECT SUM(qa_invoicesitems.item_quantity) AS item_count, COUNT(*) AS invoice_count  
FROM qa_invoices 
LEFT OUTER JOIN qa_invoicesitems USING (invoice_code) 
WHERE qa_invoices.invoice_date = 25 

我的結果:

item_count invoice_count 
8   3   

我有幾個小時尋找解決方案,問題是要統計發票(invoice_count)。

正確的結果將是:

item_count invoice_count 
8   2 

如果有人能幫助我與我的poblem。

回答

1

嘗試向您的COUNT添加DISTINCT。

SELECT SUM(qa_invoicesitems.item_quantity) AS item_count, COUNT(DISTINCT(qa_invoicesitems.invoice_code)) AS invoice_count  
FROM qa_invoices 
LEFT OUTER JOIN qa_invoicesitems USING (invoice_code) 
WHERE qa_invoices.invoice_date = 25 
+0

哇,快速有效。非常感謝 –