techkuz
techkuz

Reputation: 3956

Merge rows in postgresql

I have a table with the following values in columns:

Table (col1, col2, col3, col4, col5, col6):

    a b c d e f
    a b c g h i
    a b c k l m
    a b c n o p

As a result I want to have one row:

a b c d e f g h i k l m n o p

How to do that?

Upvotes: 1

Views: 183

Answers (2)

Zaynul Abadin Tuhin
Zaynul Abadin Tuhin

Reputation: 32003

use union and string_agg

select string_agg(distinct c ,' ') from
   (
    select col1 as c from t
    union
    select col2 from t
    union
    select col3 from t
    union
    select col4 from t
    union
    select col5 from t
    union
    select col6  from t
  ) as t1

Upvotes: 2

Yogesh Sharma
Yogesh Sharma

Reputation: 50163

I would use string_agg() :

select string_agg(t.col, ' ') 
from (select col1 as col 
      from t
      union
      select col2 
      from t
      union
      . . .
      select col6 
      from t
     ) t;

Upvotes: 1

Related Questions