Table A :
id members
____________
1 a
2 b
3 c
4 c
4 d
5 e
Table B
id countries
_____________
1 us
1 europe
1 australia
3 india
3 china
4 australia
4 canada
5 mexico
Result should look like
id members countries
___________________________
1 a us
1 europe
1 australia
2 b
3 c india
3 china
4 c australia
4 d cananda
5 e mexico
I am sorry if I am editing at wrong place.
@Martin Thanks for your reply. It works great for 2 tables. But actually I am trying to combine more than 2. Let’s say I have another table C
id prime_members
---------------------
1 p1
1 p2
I need the result to look like
id members countries prime_mem
___________________________________________
1 a us p1
1 europe p2
1 australia
2 b
3 c india
3 china
4 c australia
4 d cananda
5 e mexico
so I tried the query like this
;WITH A AS
( SELECT id, members,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY members) AS RN FROM @A ),
B AS
( SELECT id, countries,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY countries) AS RN FROM @B ),
C AS
( SELECT id,PRIME_MEM,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY PRIME_MEM) AS RN FROM @C )
SELECT COALESCE(A.id,B.id,C.ID) AS id, A.members, B.countries,C.PRIME_MEM
FROM A FULL OUTER JOIN B on A.id = B.id AND A.RN=B.RN
FULL OUTER JOIN C ON A.ID =C.ID AND C.RN = A.RN
then I got result like this:
id members countries prime_mem
___________________________________________
1 a us p1
1 europe
1 australia
1 p2
2 b
3 c india
3 china
4 c australia
4 d cananda
5 mexico
I figured it out that C.RN=B.RN gives correct output because A.RN does not have RN>1 as it has only 1 row. Here it is easy because only 3 tables and few rows. But in real time how to figure out and solve this problem. Also Table A is a reference table, i.e. values for ID in table B and C will be present in table A.
Any help is appreciated.
Thanks.
There is no “natural order” to tables so (unless there is an additional column such as id that you haven’t shown us) there is nothing that can be used to ensure that the order you have in your example source data will be preserved in the final output.
Returns (Note china and india have swapped places as my answer orders alphabetically within each group)