简体   繁体   中英

Merge two tables in SQL, with one common column

I'm trying to merge to tables in MSSQL, as in the sample below. My situation is similiar to this question. T-SQL merging two tables with common and uncommon columns

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

a b c
1 2 3
7 8 9 

Table2_test:

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 :

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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