Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 66C181337B48 for ; Sat, 16 Oct 2010 04:23:22 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.29]) (amavisd-maia, port 10024) with ESMTP id 33596-10 for ; Sat, 16 Oct 2010 07:23:15 +0000 (UTC) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from lo.gmane.org (lo.gmane.org [80.91.229.12]) by mail.postgresql.org (Postfix) with ESMTP id E21981337B4C for ; Sat, 16 Oct 2010 04:23:14 -0300 (ADT) Received: from list by lo.gmane.org with local (Exim 4.69) (envelope-from ) id 1P716l-000690-CL for pgsql-sql@postgresql.org; Sat, 16 Oct 2010 09:23:11 +0200 Received: from ppp-188-174-78-1.dynamic.mnet-online.de ([188.174.78.1]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 16 Oct 2010 09:23:11 +0200 Received: from spam_eater by ppp-188-174-78-1.dynamic.mnet-online.de with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Sat, 16 Oct 2010 09:23:11 +0200 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Thomas Kellerer Subject: Re: How to collect text-fields from multiple rows ? Date: Sat, 16 Oct 2010 09:23:03 +0200 Lines: 38 Message-ID: References: <4CB91AAE.6030602@gmx.net> Mime-Version: 1.0 Content-Type: text/plain; charset=UTF-8; format=flowed Content-Transfer-Encoding: 7bit X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: ppp-188-174-78-1.dynamic.mnet-online.de User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; de; rv:1.8.1.21) Gecko/20090302 Thunderbird/2.0.0.21 Mnenhy/0.7.5.666 In-Reply-To: <4CB91AAE.6030602@gmx.net> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-1.91 tagged_above=-5 required=5 tests=BAYES_00=-1.9, T_RP_MATCHES_RCVD=-0.01 X-Spam-Level: X-Archive-Number: 201010/40 X-Sequence-Number: 34691 Andreas wrote on 16.10.2010 05:23: > Hi, > > how can I collect text-fields from multiple rows into one output row? > I'd like to do an equivalent to the aggregate function SUM() only for text. > > The input is a select that shows among other things a numerical column where I would like to group by. > The text column of all rows in a group should get concatenated into 1 text devided by a '\n'. > > Even better would be if I could add a second text colum per line as topic. > > Input e.g. > select group_nr::integer, memo::text, topic::text ... > > 1, 'bla ', 'weather' > 2, 'yada..', 'weather' > 2, 'talk talk..', 'cooking' > 2, 'words words, ...', 'poetry' > 3, .... > > Output: > > 1, 'weather\nbla...' > 2, 'weather\nyada..\ncooking\ntalk talk..\npoetry\nwords words, ...' > If you are on 9.0: SELECT group_nr, string_agg(memo||'--'||topic, '--') FROM the_table_with_no_name GROUP BY group_nr; On 8.x you need to user array_agg() SELECT group_nr, array_to_string(array_agg(memo||'--'||topic),'--') FROM the_table_with_no_name GROUP BY group_nr;