user3723562
user3723562

Reputation: 73

Exact match of column data to be retrieved

I have scenario where i need to retrieve record only when two columns from two different tables needs to exactly match

Table A
--------
Column1 Column2
Item1    Code1
Item1    Code2
Item1    Code3
Item1    Code4

Table B
-------

Column1 Column2 Column3
Item2   Code1    10
Item2   Code2    10
Item2   Code3    10
Item2   Code4    10

Item3   Code1    10
Item3   Code2    10
Item3   Code3    10    

Now I need to get Column 3 from Table B only when All the Values in Column2 in both tables matches. item 3 should be ignored since not all the values of column2 in table B matches table A column 2

End Result I am expecting is

Column1 Column2 Column3
Item1   Code1    10
Item1   Code2    10
Item1   Code3    10
Item1   Code4    10

Suggestion pls for this SQL.

Upvotes: 0

Views: 90

Answers (1)

John Ruddell
John Ruddell

Reputation: 25842

try an inner join with a subquery.. the having clause is key here to make sure that it matches all 4 conditions.

Query

SELECT a.*, b.column3 
FROM tablea a
JOIN tableb b on b.column2 = a.column2
WHERE b.column1 IN
(   SELECT b.column1
    FROM tableB b
    WHERE b.column2 in(select column2 from tablea)
    GROUP BY b.column1
    HAVING COUNT(*) = 4
);

DEMO

OUTPUT

Column1 Column2 Column3
Item1   Code1   10
Item1   Code2   10
Item1   Code3   10
Item1   Code4   10

NOTE:

if you dont actually know the number of codes for a particular item you can also make it dynamic like this.

SELECT a.*, b.column3 
FROM tablea a
JOIN tableb b on b.column2 = a.column2
WHERE b.column1 IN
(   SELECT b.column1
    FROM tableB b
    WHERE b.column2 in(select column2 from tablea)
    GROUP BY b.column1
    HAVING COUNT(*) = (SELECT count(*) from tablea where column1 = 'Item1')
);

all you need to know is the product you want to match.. aka which item

Upvotes: 1

Related Questions