Skip to content
Advertisement

How to merge in SQL when the key variable is repeated in one of the tables?

I have a dataset with two tables. In the first, I have information about workers and in the second about companies. Each worker has an ‘id’ of the firm to which he belongs. I would like to create a new table from the merge of the worker base with the firm base, keeping the information from the two tables. The following is a minimum replicable example of the tables:

I first tried to use the operator IN:

This command returns the desired structure, but without the data of the firms (i.e., name and capital):

I also tried:

Which returns the error Error: near line 17: near" MERGE ": syntax error. As if sql is not recognizing the keyword “MERGE”.

How can I merge keeping company data?

Advertisement

Answer

You are misunderstanding the merge keyword, its purpose is for inserting and updating data from a source table against a target table, replacing the need for a seperate update where rows exist and insert where they don’t.

You don’t provide a basic example of your desired output, and you also state the query you tried gives you the expected output and at the same time is missing data… it cannot be both.

What you seem to want is just a simple join between these two tables, like so

If you want to create the result of this query as a new table, you can simply do

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement