Re: Group by a range of values

From: Steve Midgley <science(at)misuse(dot)org>
To: Mike Martin <redtux1(at)gmail(dot)com>
Cc: pgsql-sql <pgsql-sql(at)lists(dot)postgresql(dot)org>
Subject: Re: Group by a range of values
Date: 2020-08-01 18:55:47
Message-ID: CAJexoSJc_HaF3qM_SsvdpEXWnpSBfja9gBi0Kg8QixehvcZPvw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

On Sat, Aug 1, 2020 at 5:15 AM Mike Martin <redtux1(at)gmail(dot)com> wrote:

> Say I have a field of ints, as for example created by with ordinality or
> generate_series, is it possible to group by a range? eq
>
> 1,2,3,4,5,6,7,8,9,10
> step 3
> so output is
>
> 1 1
> 2 1
> 3 1
> 4 2
> 5 2
> 6 2
> 7 3
> 8 3
> 9 3
> 10 4
>
> thanks
>

*My solution would be:*
select num, ceiling(CAST (num as float)/3) as grp from Agg

*Yields:*
num grp
1 1
2 1
3 1
4 2
5 2
6 2
7 3
8 3
9 3
10 4

*For DDL of: *
CREATE TABLE Agg
("num" int);

INSERT INTO Agg
("num")
VALUES
(1),
(2),
(3),
(4),
(5),
(6),
(7),
(8),
(9),
(10);

I created this in SQL Fiddle: http://sqlfiddle.com/#!17/37519e/30/0

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Mike Martin 2020-08-03 10:39:11 Error - Arrays must contain only scalars and other arrays when array element is an array
Previous Message Rob Sargent 2020-08-01 12:53:38 Re: Group by a range of values