如何使用PostgreSQL将多行组合成一列?

时间:2015-04-23 19:18:53

标签: sql postgresql aggregate-functions

如何将多个结果合并到一列?

例如,我的查询显示以下结果:

internaldocid | document id | versionid | title | tagname
1146 | DOC-1146 | 2 | Press Release | tag1
1146 | DOC-1146 | 2 | Press Release | tag2
1146 | DOC-1146 | 2 | Press Release | tag3

我希望它能显示这个结果:

internaldocid | document id | versionid | title | tagname
1146 | DOC-1146 | 2 | Press Release | tag1, tag2, tag3

这是我的SQL:

SELECT
  cmsdocument.internaldocid,
  cmsdocument.documentid,
  cmsdocument.versionid,
  cmsdocversion.title,
  cmstag.tagname
FROM 
  public.cmsobjecttag,
  public.cmstag,
  public.cmsdocument,
  public.cmsdocversion,
  public.cmsuser
WHERE 
  cmsobjecttag.tagid = cmstag.tagid AND
  cmsobjecttag.objectid = cmsdocument.internaldocid AND
  cmsdocument.internaldocid = cmsdocversion.internaldocid AND
  cmsdocument.userid = cmsuser.userid AND
  cmsdocversion.state = 'published' AND
  cmsobjecttag.objecttype = '102';

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

自PostgreSQL版本9以来,只需使用string_agg

即可完成
SELECT
  cmsdocument.internaldocid,
  cmsdocument.documentid,
  cmsdocument.versionid,
  cmsdocversion.title,
  string_agg(cmstag.tagname, ',')
FROM 
  public.cmsobjecttag,
  public.cmstag,
  public.cmsdocument,
  public.cmsdocversion,
  public.cmsuser
WHERE 
  cmsobjecttag.tagid = cmstag.tagid AND
  cmsobjecttag.objectid = cmsdocument.internaldocid AND
  cmsdocument.internaldocid = cmsdocversion.internaldocid AND
  cmsdocument.userid = cmsuser.userid AND
  cmsdocversion.state = 'published' AND
  cmsobjecttag.objecttype = '102'
GROUP BY 
  cmsdocument.internaldocid,
  cmsdocument.documentid,
  cmsdocument.versionid,
  cmsdocversion.title