简体   繁体   English

在 SQL 中合并两个表,一个公共列

[英]Merge two tables in SQL, with one common column

I'm trying to merge to tables in MSSQL, as in the sample below.我正在尝试合并到 MSSQL 中的表,如下面的示例所示。 My situation is similiar to this question.我的情况和这个问题类似。 T-SQL merging two tables with common and uncommon columns T-SQL 合并两个具有常见列和不常见列的表

I have tried using the following query:我尝试使用以下查询:

select coalesce(t1.a, t2.a), t1.b, t1.c, t2.d, t2.k
from Table1_test t1
full outer join Table2_test t2 on t2.a = t1.a

But it results in this, where the rows that have the same value in column a, merges in the same row但结果是,在 a 列中具有相同值的行合并在同一行中

a   b   c      d    k
1   2   3      5    6
7   8   9     null  null
4 null  null   6    7
9 null  null   0    2

Table1_test:表1_测试:

a b c
1 2 3
7 8 9 

Table2_test:表2_测试:

a d k
4 6 7
1 0 2

Merged Table I want:我想要的合并表:

a   b   c      d    k
1   2   3     null  null
7   8   9     null  null
4 null  null   6    7
1 null  null   0    2

You can use the following using UNION ALL :您可以使用UNION ALL使用以下内容:

SELECT a, b, c, NULL AS d, NULL AS k FROM table1_test
UNION ALL
SELECT a, NULL, NULL, d, k FROM table2_test

You can also use the FULL OUTER JOIN with a false match condition ( 1 = 2 ):您还可以使用带有错误匹配条件 ( 1 = 2 ) 的FULL OUTER JOIN

SELECT COALESCE(t1.a, t2.a) AS a, t1.b, t1.c, t2.d, t2.k
FROM Table1_test t1 FULL OUTER JOIN Table2_test t2 ON 1 = 2

You can also generate the above SQL query (in case there are a lot of columns, or you don't want to pick the common / uncommon column names yourself):您也可以生成上面的 SQL 查询(以防有很多列,或者您不想自己选择常用/不常用的列名称):

DECLARE @sql VARCHAR(MAX) = 'SELECT ' + (
  SELECT STUFF((SELECT ',' + + col FROM (
    SELECT CASE WHEN i1.t IS NOT NULL AND i2.t IS NOT NULL THEN 'COALESCE(' + i1.t + '.' + i1.COLUMN_NAME + ', ' + i2.t + '.' + i2.COLUMN_NAME + ') AS ' + i1.COLUMN_NAME ELSE COALESCE(i1.COLUMN_NAME, i2.COLUMN_NAME) END AS col, COALESCE(i1.COLUMN_NAME, i2.COLUMN_NAME) cname FROM (
    SELECT 't1' AS t, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Table1_test'
    ) i1 FULL OUTER JOIN (
    SELECT 't2' AS t, COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Table2_test'
    ) i2 ON i1.COLUMN_NAME = i2.COLUMN_NAME

  ) cols ORDER BY cname FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
) + ' FROM Table1_test t1 FULL OUTER JOIN Table2_test t2 ON 1 = 2'

EXECUTE(@sql)

You can put the above script into a stored procedure with two parameters to make the script more flexible.可以把上面的脚本放到有两个参数的存储过程中,让脚本更加灵活。 You can find an example of the stored procedure on the demo.您可以在演示中找到存储过程的示例。

demo on dbfiddle.uk dbfiddle.uk 上的演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM