简体   繁体   中英

How to select distinct values on 2 columns in postgresql

I have a table with col A and col B . Col A and Col B can have repetitive values. I want to select distinct values from Col A and Col B individually and populate them in 1 column as unique values. How do I do that?

Example

col_a | col_b
------+------
 1    | 3 
 2    | 4 
 3    | 5 
 4    | 7 
 5    | 8  
 6    | 

I want to extract the total unique values in a table that says 1,2,3,4,5,6,7,8 . How do I do that?

You can use a UNION to combine two results with each column. A UNION will remove duplicates automatically:

select col_a as value
from the_table
union
select col_b 
from the_table;

One simple approach is to use a union:

SELECT DISTINCT val
FROM
(
    SELECT A AS val FROM yourTable
    UNION ALL
    SELECT B FROM yourTable
) t;

Demo

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