Jonathan Edgardo
Jonathan Edgardo

Reputation: 513

MySQL Left Join Duplication

TABLE A: qa_invoices

    invoice_code   invoice_date
    1              25
    2              25
    3              26
    4              27

TABLE B: qa_invoicesitems

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

My Query:

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

My Result:

item_count  invoice_count
8           3           

I have hours and hours looking for a solution to this, the problem is to count the Invoices (invoice_count).

The correct result would be:

item_count  invoice_count
8           2

if someone can help me with my poblem.

Upvotes: 0

Views: 135

Answers (1)

hafichuk
hafichuk

Reputation: 10781

Try adding DISTINCT to your COUNT.

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

Upvotes: 1

Related Questions