-3

I have two tables which I want to join. I have tried LEFT, RIGHT, INNER joins on Table but no success.

Table1

Name1  Name2
------------
A      1
B      2
C      3
D      1

Table2

Name2  Name3
------------
1      x
1      y
2      x
3      x
3      y
3      z
4      y

The result for what I am looking for is:

ResultTable

Name1 Name2 Name3
------------------
A     1     x
A     1     y
B     2     x
C     3     x
C     3     y
C     3     z
D     1     x 
D     1     y
Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42

1 Answers1

0

You can try this using SQL Server Join Reference.

Select Table1.Name1, Table1.Name2, Table2.Name3
from Table1
inner join Table2 on Table1.Name2 = Table2.Name2

Here is the implementation.

create table Table1 (Name1 varchar(5), Name2 int)
Insert into Table1 Values ('A',1), ('B',2), ('C',3), ('D',1)

create table Table2 (Name2 int, Name3 varchar(5))
Insert into Table2 
         Values (1, 'x'), (1, 'y'), (2, 'x'), (3, 'x'), (3, 'y'), (3, 'z'), (4, 'y')

Select Table1.Name1, Table1.Name2, Table2.Name3
from Table1
inner join Table2 on Table1.Name2 = Table2.Name2 

The output is as shown below.

Name1   Name2   Name3
----------------------
A       1       x
A       1       y
B       2       x
C       3       x
C       3       y
C       3       z
D       1       x
D       1       y

Online Demo

enter image description here

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42
  • Thank you, i have edited the post i made a mistake on question. The problem is with the Table2 D value, this query returs D only once without right table value. – Mark Zambrano Jan 27 '20 at 08:10
  • Please check the output it is as your expected output. Request you to accept the answer if you found it helpful. – Suraj Kumar Jan 27 '20 at 08:35
  • @SurajKumar answers can be helpful even if they don't completely answer the question, accepting an answer should be reserved for answers that fully answer the question – WhatsThePoint Jan 27 '20 at 11:41