Postgresql: convert rows to string

Trabla: Postgresql: convert rows to string

Solving:

Use

string_agg(expression, delimiter)

Example:

mytable
id;country;city
1;"USA";"New York"
2;"USA";"Odessa"
3;"Ukraine";"Kiev"
4;"Germany";"Berlin"

SELECT
  country , 
  string_agg( city, ', ')
FROM  mytable
GROUP BY country

Result:
"Germany";"Berlin"
"USA";"New York, Odessa"
"Ukraine";"Kiev"

Official Docs: http://www.postgresql.org/docs/current/static/functions-aggregate.html

Sql Example from Moodle :) :

SELECT string_agg( data.idnumber, ',' )

from

(

SELECT c.idnumber
from mdl_scorm_scoes_track tr
inner join mdl_scorm_scoes ss on tr.scoid = ss.id
inner join mdl_scorm AS sc on sc.id = ss.scorm
inner join mdl_course as c on c.id = sc.course

where tr.userid = 2

group by c.idnumber

) AS data

No comments:

Post a Comment