I have three tables in SQL and I need them to all be combined into one. I need all the fields from all the tables in the one table. All the tables contain the same fields just from three different years. I wrote a code that is:
CREATE TABLE COL_TBL_TRAINING_ALL_YEARS AS(
SELECT
COL_TBL_2010_TRN_RESULTS_new.*,
COL_TBL_TRN_RESULTS_GEMS_2011.*,
COL_TBL_TRN_RESULTS_GEMS_2012.*
FROM COL_TBL_2010_TRN_RESULTS_new,
COL_TBL_TRN_RESULTS_GEMS_2011,
COL_TBL_TRN_RESULTS_GEMS_2012
WHERE COL_TBL_2010_TRN_RESULTS_new.SYS_EMP_ID_NR = COL_TBL_TRN_RESULTS_GEMS_2011.SYS_EMP_ID_NR = COL_TBL_TRN_RESULTS_GEMS_2012.SYS_EMP_ID_NR)
And I get an incorrect syntax near the word 'AS' error and incorrect syntax near '='
I have read my SQL books and cannot seem to find an explanation on the method to do this, any help would be greatly appreciated.
You need two do two step:
Use the UNION ALL
, like it was mentioned. But if a column is missing you should use NULL
for that column.
You should insert the result in a new table.
So it should look like:
SELECT *
INTO yournewtablename
FROM (SELECT col1,
col2,
col3
FROM col_tbl_2010_trn_results_new
UNION ALL
SELECT col1,
col2,
col3
FROM col_tbl_trn_results_gems_2011
UNION ALL
SELECT col1,
col2,
NULL AS Col3
FROM col_tbl_trn_results_gems_2012) n
Here is a demo to show: SQL FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With