Click here to Skip to main content
15,890,741 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
1st how to retrieve a row whose value is greater than other table column value

2nd or retrieve value as 0 if record is not available in other table

What I have tried:

SELECT        t1.no, t1.itemcode, t1.quantity, t2.INVOICE_QTY, t1.quantity - t2.INVOICE_QTY AS 'REMAINING QTY'
FROM            t1 LEFT OUTER JOIN
                         t2 ON t1.no = t2.no
WHERE        (t1.quantity > t2.INVOICE_QTY) AND (t1.no = @no)
Posted
Updated 18-Dec-17 7:33am
v3
Comments
ZurdoDev 18-Dec-17 12:58pm    
1. SELECT *
FROM table
WHERE field1 > field2

2. SELECT *, CASE t2.someid WHEN NULL THEN 0 ELSE someField END
FROM table t1
LEFT JOIN table2 t2 ON t1.id = t2.someid

These will work but you haven't given enough details to know if they are what you need for sure or not.

1 solution

You're doing a LEFT JOIN, so the order of evaluation matters.

For records in t1 with no matching record in t2, the column t2.INVOICE_QTY will be Null. Therefore, your condition in the WHERE clause will not be met, and those records will be removed from the result.

You can either update the condition to allow for this:
SQL
... 
WHERE (t1.quantity > t2.INVOICE_QTY Or t2.INVOICE_QTY Is Null) And t1.no = @no

Or, you can move the condition to the JOIN, so that it gets applied earlier:
SQL
... 
FROM t1
LEFT OUTER JOIN t2
ON t1.no = t2.no 
And t1.quantity < t2.INVOICE_QTY
WHERE t1.no = @no
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900