Rakesh
Rakesh

Reputation: 2790

SQL Server INNER JOIN with two tables

I have two tables TableA and TableB like this:

TableA

ItemCode |Qty    |BarCode       |Brand
AC       |2      |123           |BRO       
AB       |2      |1234          |BRO       
AD       |2      |1234          |BRO    

TableB

ItemCode |Brand  |BarCode       |Qty
AC       |BRO    |123           |1
AB       |BRO    |1234          |2

I trying to get the result like Records TableA not equal to Qty of TableB and records in TableA is not in TbleB

The query I have tried is

SELECT 
    A.ItemCode AS ItmA, B.ItemCode AS ItmB, A.Qty AS AQty, B.Qty AS BQty 
FROM 
    TableA A 
INNER JOIN  
    TableB B ON A.Brand = B.Brand 
WHERE 
    (A.Qty <> B.Qty)
    AND A.ItemCode NOT IN (B.ItemCode)

I am getting result like this

ItmA   |ItmB   |AQty   |BQty
--------------------------------
AB     | AC    |  2    |  1
AD     | AC    |  2    |  1

But I am trying to get the result with ItemCode AC AND AD

Upvotes: 0

Views: 46

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1269443

If you want to get records from TableA that are not in TableB, then think LEFT OUTER JOIN:

SELECT A.ItemCode AS ItmA,B.ItemCode AS ItmB,A.Qty AS AQty,B.Qty AS BQty
FROM TableA A LEFT JOIN
     TableB B
     ON A.Brand = B.Brand
WHERE A.Qty <> B.Qty OR B.Brand IS NULL;

The rest is just applying the logic of your query.

You can also express this as:

SELECT A.ItemCode AS ItmA,B.ItemCode AS ItmB,A.Qty AS AQty,B.Qty AS BQty
FROM TableA A LEFT JOIN
     TableB B
     ON A.Brand = B.Brand AND A.Qty = B.Qty 
WHERE B.Brand IS NULL;

But I think the first version comes close to how you expressed the rules.

Upvotes: 1

Related Questions