Select distinct from multiple tables

I have multiple tables and from each table I need one column (column have same name).  But I cannot use 'UNION' because 'UNION' will put all data into one output column (worse, there is no common key between tables), Example:

table_1:

column_1
-----------
1a
1a
2b
3c
4d
5e

table_2:

column_1
-----------
6a
7b
8c
9d
9d
10e

What I'm try to do is to have output (by select distinct) from multiple tables and ouput the columns side by side, example:

tab1.column_1      tab2.column_1
----------------       ----------------
1a                       6a
2b                       7b
3c                       8c
4d                       9d
5e                       10e

This should be easy but I cannot come up with the correct 'SELECT DISTINCT' for the ouput.

Thannk you,
tranicus.
tranicusAsked:
Who is Participating?
 
Joe WoodhousePrincipal ConsultantCommented:
1> select   col, id=identity(18)
2> into     #distinct1
3> from     #test1
4> group by col
5> select   col, id=identity(18)
6> into     #distinct2
7> from     #test2
8> group by col
9> go
(5 rows affected)
(5 rows affected)

1> select A.col, B.col
2> from #distinct1 A, #distinct2 B
3> where A.id = B.id
4>
5> go
 col                            col
 ------------------------------ ------------------------------
 1a                             10e
 2b                             6a
 3c                             7b
 4d                             8c
 5e                             9d

(5 rows affected)


Note that these are in fact correct results - the string "10e" sorts before "6a".

This will table scan your base tables as well as the temp tables. You don't mention how much data you have so this could be a problem!

Good luck!
0
 
tranicusAuthor Commented:
Great Idea...  Identity columns.

Thank you,
0
 
Joe WoodhousePrincipal ConsultantCommented:
Using an identity like that doesn't work in every version, so if you're using an old version we'd have to try something else. Good luck!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.