To export a query as tab-delimited from psql:
\pset format u \pset fieldsep '\t' \o filename ... query ...
This creates an array aggregate accumulator which can then be joined into a string. Very useful for combining m-m lookup data onto one line:
CREATE AGGREGATE array_accum (anyelement) (
sfunc = array_append,
stype = anyarray,
initcond = '{}'
);
Here's an example query using it that pulls out ERM information grouped by subject, including the content types which are aggregated onto one line:
SELECT s.subject, em.key, sm.rank, rt.resource_type, array_to_string(array_accum(ct.content_type), ',') AS content_types FROM erm_main em JOIN erm_subjects_main sm ON ( sm.erm_main = em.id ) JOIN erm_subjects s ON ( sm.subject = s.id ) LEFT OUTER JOIN erm_resource_types rt ON ( em.resource_type = rt.id) LEFT OUTER JOIN erm_content_types_main ctm ON ( ctm.erm_main = em.id ) LEFT JOIN erm_content_types ct ON ( ctm.content_type = ct.id ) WHERE em.site=1 GROUP BY s.subject, sm.rank, em.key, rt.resource_type ORDER BY s.subject, sm.rank DESC, em.key;
