Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combined 2 columns into one column SQL

Tags:

sql

postgresql

I'm a beginner to Postgres and need to do something like this. My Postgres query output has 2 columns. I need to combine these two like below.

Column 1:

A
B
C

Column 2:

D
D
D

Output Column:

A
B
C
D

(all values from column 1 and distinct values from column 2)

Is this possible in PostgreSQL?

like image 513
weeraa Avatar asked Mar 28 '16 18:03

weeraa


People also ask

How do I combine multiple columns into one column in SQL Server?

Select the same number of columns for each query. Corresponding columns must be the same general data type. Corresponding columns must all either allow null values or not allow null values. If you want to order the columns, specify a column number because the names of the columns you are merging are probably different.

How do I make multiple columns into one in SQL?

(each row of #t is presented 3 times, for а=1 and а=2 and а=3). For the first case we take value from Column1, and for the second - from Column2 and for the Third - from Column3. Here, certainly, there is both union and join but, in my opinion, the title's question means single scanning the table.

How do I select multiple columns as single column in SQL?

Now you know how to select single columns. In the real world, you will often want to select multiple columns. Luckily, SQL makes this really easy. To select multiple columns from a table, simply separate the column names with commas!


2 Answers

Hi there is one fancy way:

select distinct unnest(array[
        column1
        , column2
    ])
from table
like image 108
Dimo Boyadzhiev Avatar answered Nov 09 '22 00:11

Dimo Boyadzhiev


You need something like this :

 select  col    from (
   select Column1 as col   from <your table >
    union all 
    select distinct Column2 as col   from <your table>
) as myview order by col 
like image 22
elirevach Avatar answered Nov 09 '22 01:11

elirevach