Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id EC78A632E56 for ; Thu, 22 Jul 2010 08:31:43 -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 19682-06 for ; Thu, 22 Jul 2010 11:31:37 +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 290EE632BFA for ; Thu, 22 Jul 2010 08:31:35 -0300 (ADT) Received: from list by lo.gmane.org with local (Exim 4.69) (envelope-from ) id 1Obtzv-0005KN-5I for pgsql-sql@postgresql.org; Thu, 22 Jul 2010 13:31:31 +0200 Received: from g231144196.adsl.alicedsl.de ([92.231.144.196]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Thu, 22 Jul 2010 13:31:31 +0200 Received: from tim by g231144196.adsl.alicedsl.de with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Thu, 22 Jul 2010 13:31:31 +0200 X-Injected-Via-Gmane: http://gmane.org/ Mail-Followup-To: pgsql-sql@postgresql.org To: pgsql-sql@postgresql.org From: Tim Landscheidt Subject: Re: grouping subsets Date: Thu, 22 Jul 2010 11:31:23 +0000 Organization: Lines: 38 Message-ID: References: <20100722100226.GE10348@a-kretschmer.de> <4C48230D.7030304@archonet.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Complaints-To: usenet@dough.gmane.org X-Gmane-NNTP-Posting-Host: g231144196.adsl.alicedsl.de Mail-Copies-To: never User-Agent: Gnus/5.13 (Gnus v5.13) Emacs/23.1 (gnu/linux) Cancel-Lock: sha1:JeUWHdoTnq/oKr1I7xIINNkPNdU= 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: 201007/92 X-Sequence-Number: 34405 Richard Huxton wrote: >>> What I want to get is the values grouped by "subset", where a subset is a set of rows with identical column until the colum changes. >>> Is there a way to get >>> | 2 | B | >>> | 4 | C | >>> | 4 | B | >>> | 3 | D | >>> by SQL only? >> I think, the problem is that there are 2 identical groups. I think, you >> can write a pl/pgsql-proc, selecting all ordered by the date-field and >> walking through the result to do the grouping, checking if the 2nd >> column is different from the previous. >> With plain SQL it's maybe possible too, but i don't know how ... > It should be do-able in 8.4 onwards, look into windowing > functions. In particular the lag() function: > SELECT > mycode, > mydate, > lag(mycode) OVER (ORDER BY mydate) AS prev_code > FROM > mytable > ORDER BY mydate; > It should be possible to use that as a subquery with an > outer query that compares mycode=prev_code to get a run > length. Hmmm. Can the outer query be done without using "WITH RECURSIVE"? Tim