Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
180 views
in Technique[技术] by (71.8m points)

sql - Inserting data scattered from multiple tables into a table

I'm at beginners level in SQL and I hope that get guidance.

Table 1, 2 and 3 are Tables without a UniqueID.

TABLE1

enter image description here

TABLE2

TABLE3

Then I inserted all records of the 3 tables into Table4 with a uniqueID and source table column.

TABLE4

enter image description here

My goal is to insert data from Table 4 INTO Table5 but instead of creating an update statement on each NULL records per column. Is there a better way to insert it in one query? I tried using row partition and case function but it doesn't work.

Desired Table5 output.

Edit: For EZRA FITCH STATE = OREGON, it is entered according to the table rank. Rank 1=Table1 Rank 2=Table2 Rank 3=Table3

enter image description here

question from:https://stackoverflow.com/questions/65877481/inserting-data-scattered-from-multiple-tables-into-a-table

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

use this code:

 INSERT INTO Table4 (FirstName, LastName, State, Position, EmploymentStatus, Source)
        SELECT FirstName, LastName, State, Position, EmploymentStatus, 'Table1' FROM Table1;
        
    INSERT INTO Table4 (FirstName, LastName, State, Position, EmploymentStatus, Source)
        SELECT FirstName, LastName, State, Position, EmploymentStatus, 'Table2' FROM Table2;
        
    INSERT INTO Table4 (FirstName, LastName, State, Position, EmploymentStatus, Source)
        SELECT FirstName, LastName, State, Position, EmploymentStatus, 'Table3' FROM Table3;


 INSERT INTO Table5(FirstName, LastName, State, Position, EmploymentStatus)
  SELECT
    MAX(FirstName),MAX(LastName),MAX(State),MAX(Position),MAX(EmploymentStatus)
FROM table4
group by FirstName , LastName

this code work

table5 output: enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...