Skip to main content

Let's say I have two tables: 

 - TABLE A: User ID, many other cols. .PK is User ID]

 - TABLE B: User ID, many other cols. sMany lines per User ID]

 

Is there any way I can go through each User ID in TABLE A and do in the SQL transformation something such as:

 

Declare TABLE C

 

for each User ID in TABLE A

  • Append TABLE A.User ID, TABLE A.Name in TABLE C
  • Select * from TABLE B where TABLE B.User Id = TABLE A.User Id
  • Append TABLE B.User ID, TABLE B.Other Field in TABLE C

 

The idea would be to create a table in which you can find each line in TABLE A followed by every line for that same ID in TABLE B.

 

Sorry for the poor SQL terminology, as I am not very used to it.

 

Thank you so much in advance.

Hi Mikel,

If I understood your problem correctly, Table C is a new table that you want to create from a combination of columns from Table A and Table B.

So I don't think you really mean Append when you "declare" table C. (Append means vertically sticking 2 tables together, first each row from one table then each row from the second one, taking the column structure into account.)

I think what you mean, is merge.

And that can be achieved by a LEFT JOIN.

Something like:

CREATE TABLE TABLE_C AS (

   SELECT

         TABLE_A.ID

       , TABLE_A.NAME

       , TABLE_B.*

   FROM

       TABLE_A LEFT JOIN

       TABLE_B ON

       TABLE_A.ID = TABLE_B.ID

   )

TABLE_B.* means every column from TABLE_B but of course you can also just list all the columns you actually need.

 This take ID and NAME columns from TABLE_A and adds all corresponding information from TABLE_B (when available).

 

 

 


Good afternoon,

 

No, what I am actually looking for is a way to append many selects. I need to combine two tables by appending line 1 in table A with lines 1 to 6 in table B, line 2 in table A with lines 7 to 10 in table B... the way to choose the number of lines in table B depends on the User ID. That is why I was thinking on doing it by going through the lines in table A and append each iteration the line in table A with the lines in table B.

 

Thank you,


Append would still only work for the same columns in Table A and B.

If this is your table A:

imageAnd this is your table B:

imageThe code I suggested would give you the following table C:

imageIf this is not the outcome you are looking for, please provide some example data for better understanding the problem.


Reply