Search code examples
sqlsql-serverjoinleft-join

How do I join identical columns while also keeping separate unique columns from two tables?


I have two tables, E and P.

E:

Col 1 Col 2 Col 3 Col 4
Val A Val C Val E Val X
Val B Val D Val F Val Y

P:

Col 1 Col 2 Col 3 Col 5
Val A Val C Val E Val Z
Val B Val D Val F Val K

where Columns 1, 2, and 3 in both tables are identical in terms of both the name of the column and the values but column 4 in table E and column 5 in table P both have unique values.

How do I join these two tables so that I get:

EP:

Col 1 Col 2 Col 3 Col 4 Col 5
Val A Val C Val E Val X Val Z
Val B Val D Val F Val Y Val K

I have tried:

select  

p.[Col 1],

p.[Col 2],

p.[Col 3],

e.[Col 1],

e.[Col 2],

e.[Col 3],

p.[Col 5],

e.[Col 4]

from p

left join e on p.[Col 3] = E.[Col 3] and p.[Col 2] = e.[Col 2] and p.[Col 1] = e.[Col 1]

group by p.[Col 1], p.[Col 2], p.[Col 3], e.[Col 1], e.[Col 2], e.[Col 3]

But what I get is:

Col 1 Col 2 Col 3 Col 1 Col 2 Col 3 Col 4 Col 5
Val A Val C Val E Val A Val C Val E Val X Val Z
Val B Val D Val F Val B Val D Val F Val Y Val K

Solution

  • I think you're over complicating it substantially here.

        SELECT 
            p.[Col 1],
            p.[Col 2],
            p.[Col 3],
            e.[Col 4] AS [Col 4],
            p.[Col 4] AS [Col 5],
        FROM p INNER JOIN 
            e ON (p.[Col 3] = E.[Col 3] and p.[Col 2] = e.[Col 2] and p.[Col 1] = e.[Col 1])