2

I have the following tables and would like to get the result as follow

Table po
ID | Date
1  | 20-Jun-2016

Table podetails
ID | poid | itemcode | quantity
1  | 1    | SOAP123  | 100

Table poreceived
ID | poid | itemcode | quantity
1  | 1    | SOAP123  | 20
2  | 1    | SOAP123  | 60

Result should be:

PO | Date        | itemcode | quantity
1  | 20-Jun-2016 | SOAP123  | 80

What I have done is:

SELECT 
    po.id, podetails.itemcode, poreceived.quantity
FROM
    po
        LEFT JOIN
    podetails ON podetails.poid = po.id
        LEFT JOIN
    poreceived ON poreceived.poid = podetails.poid

But the result is not what I expected.

Any help would be appreciate it.

1
  • 1
    When results are unexpected, it would be useful to show them or to explain in what ways they are unexpected. Commented Jun 20, 2016 at 5:37

1 Answer 1

2

It looks like you need to do an aggregation of the poreceived table by poid. You can use a subquery for this:

SELECT po.id, COALESCE(podetails.itemcode, 'NA'), COALESCE(t.quantity, 0)
FROM po
LEFT JOIN podetails
    ON podetails.poid = po.id
LEFT JOIN
(
    SELECT poid, itemcode, SUM(quantity) AS quantity
    FROM poreceived
    GROUP BY poid, itemcode
) t
    ON t.poid = podetails.poid AND t.itemcode = podetails.itemcode

Other than the aggregation problem, your query strategy looked correct. I also added COALESCE to the columns from the podetails and poreceived tables in case the id from po does not match to anything.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks Tim. But when you have another row in podetails with the same poid number with different itemcode, then the quantity result is not correct for each item. Any idea?
@Santana I updated my query to include the itemcode in the join condition.
Good answer, although I find COALESCE inappropriate here (converting quantity to string, only to replace NULL with '' which even look identical in many tools).
@ThorstenKettner Thanks for the comments.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.