Question

ad_org table with column id & name

ad_org

            ad_org_id             |   name    
----------------------------------+-----------

 357947E87C284935AD1D783CF6F099A1 | Spain

 43D590B4814049C6B85C6545E8264E37 | Main

 5EFF95EB540740A3B10510D9814EFAD5 | USA

 2878085215E54C73A04D394BFD170733 | India

 22669845D93A49A98932CE29AE02E0FD | Honkong

how to get output of all names(in 1 string) in this way from the above database

Spain | Main | USA | India | Honkong

in 1 select statement.

Was it helpful?

Solution

Use string_agg.

SELECT string_agg("name", ' | ') FROM thetable;

For older PostgreSQL, you must use array_agg and array_to_string:

SELECT array_to_string( array_agg("name"), ' | ') FROM thetable;

If you want a particular order, put it in the aggregate, e.g for alphabetical:

SELECT string_agg("name", ' | ' ORDER BY "name") FROM thetable;

OTHER TIPS

use below code

DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX)

select @cols = STUFF((SELECT ',' + QUOTENAME(ColumnName) from yourtable group by ColumnName, id order by id FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'')

set @query = 'SELECT ' + @cols + ' from ( select value, ColumnName from yourtable ) x pivot ( max(value) for ColumnName in (' + @cols + ') ) p '

execute(@query)

Click here for Demo

got it by searching..

Equivalent to PostgreSQL array() / array_to_string() functions in Oracle 9i

select array_to_string(array(select name from ad_org), '|') as names;

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top