From: Steve Midgley <science@misuse.org>
To: Mike Martin <redtux1@gmail.com>
Cc: pgsql-sql <pgsql-sql@lists.postgresql.org>
Subject: Re: Group by a range of values
Date: Sat, 1 Aug 2020 11:55:47 -0700
Message-ID: <CAJexoSJc_HaF3qM_SsvdpEXWnpSBfja9gBi0Kg8QixehvcZPvw@mail.gmail.com> (raw)
In-Reply-To: <CAOwYNKYcQR_Fzx0=L+5LBh6zqDXQuA3_a+ggAm5RZ3G6zHNbOQ@mail.gmail.com>
References: <CAOwYNKYcQR_Fzx0=L+5LBh6zqDXQuA3_a+ggAm5RZ3G6zHNbOQ@mail.gmail.com>
On Sat, Aug 1, 2020 at 5:15 AM Mike Martin <redtux1@gmail.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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-sql@postgresql.org
Cc: science@misuse.org, redtux1@gmail.com
Subject: Re: Group by a range of values
In-Reply-To: <CAJexoSJc_HaF3qM_SsvdpEXWnpSBfja9gBi0Kg8QixehvcZPvw@mail.gmail.com>
References: <CAOwYNKYcQR_Fzx0=L+5LBh6zqDXQuA3_a+ggAm5RZ3G6zHNbOQ@mail.gmail.com> <CAJexoSJc_HaF3qM_SsvdpEXWnpSBfja9gBi0Kg8QixehvcZPvw@mail.gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox