I have 2 table with below structure :
Table 1 (Tb1) :
MasId Int, ItemId int, Quantity int
1 1 10
1 2 5
1 3 18
2 2 3
2 4 8
Table 2 (Tb2) :
MasId Int, ItemId int, Quantity int
10 1 10
10 2 5
10 3 18
6 2 3
6 4 8
I want to match Tb1 with Tb2 with ItemId and Quantity Columns. and get below query :
Tb1.MasId Tb2.MasId
1 10
2 6
Table1 and Table2 contain about 2000000 record. and I use SQL Server 2012
EDIT 1
In Tb1 and Tb2 exists records such below :
Tb1:
MasId, ItemId, Quantity
3 15 10
3 16 2
Tb2:
MasId, ItemId, Quantity
20 15 10
20 18 5
Tb1.MasId and Tb2.MasId is not matched together.
The following query available as a SqlFiddle returns correct results even with tricky data:
The other answers on the page give incorrect results with the sample data in my SqlFiddle. Specifically, adding the following data to
Tb2will break X.L.Ant’s current query (which will show a false match2, 8due to not detecting that the8, 3, 18doesn’t belong).