如何在一个相似的列上联接两个表,在另一个列上联接任何余数

时间:2018-10-20 18:49:38

标签: sql sql-server

所以我有: 查看_1

ID | col1 | col2 | col3
---+------+------+-----
1  | a200 | null | 5
2  | null | 300  | 6

View_2:

ID | colA | colB | colC
---+------+------+-----
1  | a200 | 400  | 40
2  | a500 | 300  | 60

我想做的是将视图1加入到View_1.col1 = View_2.colA的视图2上,并使用辅助列View_1.col2 = View_2.colB ...将剩余的View_1行添加到View 2上。像这样的东西:

| a200 | 400 | 5 | 40
| a500 | 300 | 6 | 60

我认为做两个单独的内部联接,然后由联合会做我想要的事情……但是我想我得到了额外的数据。

通过一列进行初始联接的最佳方法是什么,然后任何不匹配的行都会查看它们与View 2之间是否存在内部联接,但在另一列上?

2 个答案:

答案 0 :(得分:2)

你可以喜欢

CREATE TABLE View_1
(
ID INT,
Col1 VARCHAR(20),
Col2 INT,
Col3 INT
);

CREATE TABLE View_2
(
ID INT,
ColA VARCHAR(20),
ColB INT,
ColC INT
);

INSERT INTO View_1 VALUES
(1, 'a200', null, 5),
(2, null, 300 , 6);

INSERT INTO View_2 VALUES
(1, 'a200', 400, 40),
(2, 'a500', 300, 60);

SELECT COALESCE(V1.Col1, V2.ColA) Column1,
       COALESCE(V1.Col2, V2.ColB) Column2,
       V1.Col3 Column3,
       V2.ColC Column4
FROM View_1 V1 INNER JOIN View_2 V2
     ON V1.Col1 = V2.ColA OR V1.Col2 = V2.ColB;

结果:

+----+---------+---------+---------+---------+
|    | Column1 | Column2 | Column3 | Column4 |
+----+---------+---------+---------+---------+
|  1 | a200    |     400 |       5 |      40 |
|  2 | a500    |     300 |       6 |      60 |
+----+---------+---------+---------+---------+

Demo

答案 1 :(得分:0)

您可以仅将ORINNER JOIN一起使用,然后使用CASE Statements返回非null,此解决方案将返回您要返回的示例:

DECLARE @temp1 TABLE ([Id] INT IDENTITY(1, 1), [col1] varchar(10), [col2] INT, [col3] INT)
DECLARE @temp2 TABLE([Id] INT IDENTITY(1, 1), [col1] varchar(10), [colB] INT, [colC] INT)

INSERT INTO @temp1
([col1], [col2], [col3])
VALUES('a200', NULL, 5), (NULL, 300, 6)

INSERT INTO @temp2
([col1], [colB], [colC])
VALUES('a200', 400, 40), ('a500', 300, 60)

SELECT CASE WHEN t1.[col1] IS NULL THEN t2.[col1] ELSE t1.[col1] END AS [col1], CASE WHEN t1.[col2] IS NULL THEN t2.[colB] ELSE t1.[col2] END AS [col2], t1.[col3], t2.[colC]
FROM @temp1 AS t1
INNER JOIN @temp2 AS t2
ON t2.[col1] = t1.[col1] OR t2.[colB] = t1.[col2]