Re: Grouping, Aggregate, Min, Max - Mailing list pgsql-general

From Rémi Cura
Subject Re: Grouping, Aggregate, Min, Max
Date
Msg-id CAJvUf_vvE0WycAdY4He3Q9ApfzrGkn4ZwLfVRBczjyNZaKWyBQ@mail.gmail.com
Whole thread Raw
In response to Grouping, Aggregate, Min, Max  (Misa Simic <misa.simic@gmail.com>)
Responses Re: Grouping, Aggregate, Min, Max
List pgsql-general
There is a trick to simplify the thing and avoid using aggregates :

Cheers,
Rémi-C


2013/12/13 Misa Simic <misa.simic@gmail.com>
Hi All,

I am not sure how to define with words what I want to accomplish (so can't ask google the right question :) )

So will try to explain with sample data and expected result:

Scenario 1)

idthing_idcategoryperiod_id
11A1
21A2
31A3
41A4
51A5
61A6
71A7
81A8
91A9
102A1
112A2
122A3
132A4



Expected result:

thing_idcategoryperiods
1A1-9
2A1-4

(Sounds easy, group by, thing_id, category use Min and Max for period id - but further scenarios makes it a bit complicated...)

Scenario 2)

idthing_idcategoryperiod_id
11A1
21A2
31A3
41A4
51B5
61B6
71B7
81A8
91A9
102A1
112A2
122A3
132A4

Expected result:
thing_idcategoryperiods
1A1-4, 8-9
1B5-7
2A1-4

Scenario 3)

idthing_idcategoryperiod_id
11A1
21A2
31A3
41A7
51A8
61A9
72A1
82A2
92A3
102A4

Expected result:

thing_idcategoryperiods
1A1-3, 7-9
2A1-4



So goal is, to group by thing_id, category id - but if period_id is interupted (not in incremented by 1) to have aggregated spans...

To desired results we have came up using several CTE's (what makes a query a bit big, and more "procedural way": make cte what calculated diff between current and previous row, next cte uses previous one to define groupings, next cte to make aggregates etc...)

So I wonder - is there some kind of aggregate window function what does desired results?


Many Thanks,

Misa


pgsql-general by date:

Previous
From: Misa Simic
Date:
Subject: Grouping, Aggregate, Min, Max
Next
From: Misa Simic
Date:
Subject: Re: Grouping, Aggregate, Min, Max