0

I know it sounds easy when appending a entire row to new table, but this is different

This is Table 1

This is Table 2

This is Table 3

Question 1, state to combine the Table 1 and Table 2 and keep duplicate value, to create a new table, I have used the following query:

CREATE TABLE EMP_TBL_3
(
    EMP_ID int,
    Name varchar(255),
    DOJ int
);

INSERT INTO EMP_TBL_3 (EMP_ID, Name, DOJ)
   SELECT * FROM EMP_TBL_1 
   UNION ALL
   SELECT * FROM EMP_TBL_2;

Results:

Answer

Now the problem arise at 2nd question, saying: Take the D.O.B from EMP_BRTH_REC and combine them to EMP_TBL_3:

I have tried this query:

ALTER TABLE EMP_TBL_3
ADD DOB int;

SELECT * FROM EMP_TBL_3;

SELECT EMP_ID, Name, DOJ, DOB
FROM EMP_TBL_3
UNION ALL
SELECT EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
FROM EMP_BRTH_REC 
LEFT JOIN EMP_TBL_3 ON EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;

Results:

Error Result

My desired output is:

enter image description here

How do I do that?

4
  • 1
    So you're attempting this on 3 type of DBMS? Commented Feb 19, 2020 at 4:26
  • I've removed the RDBMS tags - please add back the one of interest. Commented Feb 19, 2020 at 4:29
  • tcadidot0 Correct Commented Feb 19, 2020 at 4:40
  • Dale K, I've added the tag! Commented Feb 19, 2020 at 4:43

2 Answers 2

1

If i undertand propery, you just need to do this:

select EMP_TBL_3.EMP_ID, EMP_TBL_3.Name, EMP_TBL_3.DOJ, EMP_BRTH_REC.DOB
from EMP_BRTH_REC LEFT JOIN
     EMP_TBL_3
     on EMP_BRTH_REC.EMP_ID = EMP_TBL_3.EMP_ID;
Sign up to request clarification or add additional context in comments.

Comments

0

You are twice inserting the records using UNION ALL. I would suggest you to truncate and reload data into Tbl3 as given below:

ALTER TABLE EMP_TBL_3
ADD DOB int;

TRUNCATE TABLE Emp_Tbl_3;

INSERT INTO Emp_Tbl_3(Emp_Id, Name, DOJ, DOB)
SELECT EMP_TBL_1.EMP_ID, EMP_TBL_1.Name, EMP_TBL_1.DOJ, EMP_BRTH_REC.DOB
from 
EMP_BRTH_REC 
LEFT JOIN EMP_TBL_1
on EMP_BRTH_REC.EMP_ID = EMP_TBL_1.EMP_ID
UNION ALL
SELECT EMP_TBL_2.EMP_ID, EMP_TBL_2.Name, EMP_TBL_2.DOJ, EMP_BRTH_REC.DOB
from 
EMP_BRTH_REC 
LEFT JOIN EMP_TBL_2
on EMP_BRTH_REC.EMP_ID = EMP_TBL_2.EMP_ID;

1 Comment

This is right, but am getting additional 8 rows instead! i need only 8 rows

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.