简体   繁体   中英

SQL Query to get Distinct Values of all column values in a table

How to retrieve distinct values from all columns in a Table.

Select Distinct col1, col2, col3, col4 from table1 will give the unique records by checking the equality of all the columns. But I need all disctinct values from a table? Thanks in advance.

For Ex: My table has below records:

Col1                  Col2                  Col3                    Col4
------------------------------------------------------------------------ 
Melbourne             Sit1                  10.0                    5.3 
Melbourne             Sit2                  10.1                    5.4 
Sydney                Sit1                  10.0                    5.3 
Sydney                Sit3                  10.0                    5.3 
Bangalore             Sit1                  10.5                    0.1

The end result should be like below:

Result
----------------
Melbourne
Sydney
Bangalore
Sit1
Sit2
Sit3
10.0
10.1
10.5
5.3
5.4
5.1

Order doesn't matter.

You can do it like this:

select col1 from table union
select col2 from table union
. . .
select coln from table;

The use of union removes duplicate values. Note that this assumes that the column types are compatible (such as all being strings).

EDIT:

If the column in a table has to have only one type. (Okay, it could be a variant, but that is probably not a simplification.) You can cast everything to varchar2() :

select cast(col1 as varchar2(255)) from table union
select cast(col2 as varchar2(255)) from table union
. . .
select cast(coln as varchar2(255)) from table;

Alternatively, you could group the columns by data type and do a separate run for each one, or a separate column for each data type. It is unlikely that you will have exact matches across data types, so this might meet your need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM