sql to display all names in 1 row (1 string)

核能气质少年 提交于 2019-12-13 05:06:27

问题


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.


回答1:


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;



回答2:


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




回答3:


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;



来源:https://stackoverflow.com/questions/22811082/sql-to-display-all-names-in-1-row-1-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!