We help IT Professionals succeed at work.

SQL - Appending data from another table with different column names

tmajor99
tmajor99 asked
on
how can i append data from another table with different column names..  

Table 1:                                        Table 2:

Group         ID                              SectionGroup            PartID
--------      --------                     ----------------         -----------
100             A                                300                            C
200             B

Expected Result:

Group         ID
-------       -----
100             A
200             B
300             C
Comment
Watch Question

Senior Manager
CERTIFIED EXPERT
Commented:

You are looking for a "UNION"


SELECT [GROUP] AS 'Group',
               [ID]           AS 'Id'
FROM dbo.Table1
UNION 
SELECT [SectionGroup] AS 'Group',
               [PartID]             AS 'Id'
FROM dbo.Table2;


Reference:   https://docs.microsoft.com/en-us/sql/t-sql/language-elements/set-operators-union-transact-sql?view=sql-server-ver15

Scott PletcherSenior DBA
CERTIFIED EXPERT
Most Valuable Expert 2018
Distinguished Expert 2019

Commented:

Just fyi, you don't need the column names on the second(+) query in a UNION, SQL uses the names from the first query.  This is fine:


SELECT [GROUP] AS 'Group',[ID] AS 'Id'

FROM dbo.Table1

UION

SELECT [SectionGroup], [PartId]

FROM dbo.Table2