1

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?

4
  • 1
    Columns names with incremention in one table are suspect and a good candidate for normalization.. Then you should have simply done SELECT DISTINCT col FROM table Commented Oct 11, 2018 at 10:36
  • 2
    Your question is not quite as clear as you think it is. A SQL query has a fixed number of columns. How many columns are in your result set? Commented Oct 11, 2018 at 10:51
  • @GordonLinoff, 15 Commented Oct 11, 2018 at 10:55
  • 1
    Pretty much easier would be to make a pivot query which supports up the 26 columns for a-z range and set the other columns to NULL if there isn't matching data.. Then you won't have to implement PostgreSQL's dynamic SQL feature to generate columns on the fly. Commented Oct 11, 2018 at 11:06

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.