I am wanting to create a new view based on joining three tables.
table 1 and table 2 have the same column names but the data in them is representative of different time frames. The third table has columns that are unique in both tables.
My query takes all data of table1 and uses a column in table 1 to extract all records from table 2 that have a match.
and then merge this combined dataset with the third table where ever date is greater than '2017-12-01'
SELECT *
FROM table1
LEFT JOIN table2
ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3
ON table3.lookup_column = table1.lookup_column
AND table3.date >= '2017-10-01'
When I run this query to create the new view
select * into new_table
FROM table1
LEFT JOIN table2
ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3
ON table3.lookup_column = table1.lookup_column
AND table3.date >= '2017-10-01'
I get the error :
Column names in each table must be unique. Column name 'abc' in table 'new_table' is specified more than once.
How can I avoid this problem between the two tables where the column names are the exactly the same? or how can I specify that I want to combine table 1 and table 2 on column names?
Edit:
input
table 1 table2 table
col1 col2 col1 col2 col3 col4
abc def ghi jkl mno pqr
Output:
col1 col2 col3 col4
abc def mno pqr
ghi jkl mno pqr
Looking at the expected output, and the fact that table1 and table2 are structurally identical, you probably want UNION
:
SELECT table1.foo, table1.bar, table3.*
FROM table1
LEFT JOIN table2 ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3 ON table1.lookup_column = table3.lookup_column AND table3.date >= '2017-10-01'
UNION ALL
SELECT table2.foo, NULL, table3.*
FROM table1
LEFT JOIN table2 ON table1.lookup_column = table2.lookup_column
LEFT JOIN table3 ON table1.lookup_column = table3.lookup_column AND table3.date >= '2017-10-01'