如何将两个表中相同的列合并,同时保留各自独特的列?

huangapple go评论44阅读模式
英文:

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

问题

我尝试了以下查询,但是得到的结果是:

| 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 |

你想要的结果是:

| 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 |

为了获得你想要的结果,你可以尝试以下查询:

select
    p.[Col 1],
    p.[Col 2],
    p.[Col 3],
    e.[Col 4],
    p.[Col 5]
from p
left join e on p.[Col 1] = e.[Col 1] and p.[Col 2] = e.[Col 2] and p.[Col 3] = e.[Col 3]

这应该会给你期望的结果。

英文:

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

答案1

得分: 0

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])
英文:

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])

huangapple
  • 本文由 发表于 2023年2月14日 21:33:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75448593.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定