Received: from maia.hub.org (maia-5.hub.org [200.46.204.29]) by mail.postgresql.org (Postfix) with ESMTP id 5789B6338C1 for ; Thu, 22 Jul 2010 07:53:21 -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 03743-09 for ; Thu, 22 Jul 2010 10:53:14 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.7.6 Received: from relay.ptn-ipout02.plus.net (relay.ptn-ipout02.plus.net [212.159.7.36]) by mail.postgresql.org (Postfix) with ESMTP id BA40E6327CC for ; Thu, 22 Jul 2010 07:53:13 -0300 (ADT) X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: AvsEACfAR0xUXeb6/2dsb2JhbACfdnHAVoU2BA Received: from outmx05.plus.net ([84.93.230.250]) by relay.ptn-ipout02.plus.net with ESMTP; 22 Jul 2010 11:53:02 +0100 Received: from 84-51-143-99.archon037.adsl.metronet.co.uk ([84.51.143.99] helo=server3.office.archonet.com) by outmx05.plus.net with esmtp (Exim) id 1ObtOf-0006Ip-LI; Thu, 22 Jul 2010 11:53:01 +0100 Received: from [192.168.0.36] (dell36outside.office.archonet.com [192.168.0.36]) by server3.office.archonet.com (Postfix) with ESMTPA id 421D727408D; Thu, 22 Jul 2010 11:53:01 +0100 (BST) Message-ID: <4C48230D.7030304@archonet.com> Date: Thu, 22 Jul 2010 11:53:01 +0100 From: Richard Huxton User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.1.9pre) Gecko/20100217 Lightning/1.0b1 Shredder/3.0.3pre MIME-Version: 1.0 To: "A. Kretschmer" CC: pgsql-sql@postgresql.org Subject: Re: grouping subsets References: <20100722100226.GE10348@a-kretschmer.de> In-Reply-To: <20100722100226.GE10348@a-kretschmer.de> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.1 tagged_above=-5 required=5 tests=BAYES_50=0.8, RCVD_IN_DNSWL_LOW=-0.7 X-Spam-Level: X-Archive-Number: 201007/91 X-Sequence-Number: 34404 On 22/07/10 11:02, A. Kretschmer wrote: > In response to Rainer Stengele : >> 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. -- Richard Huxton Archonet Ltd