1

I have a table data like this:

Table structure

I want to concatenate the data as below in postgresql:

Desired Output

I used query as below but there is a small problem:

select 
    Item,
    array_to_string(array_agg(Component) ,', ') AS Component,
    array_to_string(array_agg(Seller) ,', ') AS Seller
from tablename
group by Item

Its giving me below output:

Giving output

For item A2, its showing C89 two times, I want to show only one time.

Please help me out!!

2 Answers 2

5

Use distinct, you also don't need array_agg():

select item, 
       string_agg(distinct component, ',') as component,
       string_agg(distinct seller, ',') as seller
from tablename
group by item;
Sign up to request clarification or add additional context in comments.

Comments

1

This should work, sometimes you need to tell it how to order the distinct

select 
    Item,
    array_to_string(array_agg(DISTINCT Component ORDER BY Item DESC ) ,', ') AS Component,
    array_to_string(array_agg((DISTINCT Seller ORDER BY Item DESC) ,', ') AS Seller
from tablename
group by Item

1 Comment

The order by item is useless because of the group by item which means all values that are aggregated will have the same value for the column item

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.