Re: Limiting to sub-id in a query ?

From: "David G(dot) Johnston" <david(dot)g(dot)johnston(at)gmail(dot)com>
To: Tim Smith <randomdev4+postgres(at)gmail(dot)com>
Cc: pgsql-general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Limiting to sub-id in a query ?
Date: 2016-10-26 16:30:01
Message-ID: CAKFQuwYv3qY1uH_4_8jkKJaxoGH56tyEJO2fgGktyieCvsNgaA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Oct 26, 2016 at 9:22 AM, Tim Smith <randomdev4+postgres(at)gmail(dot)com>
wrote:

> Hi,
>
> I've been trying various GROUP BY but these all end up erroring out,
> so maybe I'm using the wrong tool for the job (or, more likely, the
> required query is beyond my level of SQL-fu !).
>
> CREATE TABLE IF NOT EXISTS names (
> main_id bigint,
> sub_id bigint,
> name text
> );
>
> create unique index IF NOT EXISTS name_idx on names(main_id,sub_id);
> insert into names(main_id,sub_id,name) values(1,2,'Bob');
> insert into names(main_id,sub_id,name) values(1,1,'Baby Bob');
> insert into names(main_id,sub_id,name) values(100,200,'Tom');
> insert into names(main_id,sub_id,name) values(100,100,'Jerry');
>
>
> The desired output is one row per main_id, with the desired row being
> the one with the lowest sub_id, i.e.
>
> select.......
>
> main_id | sub_id | name
> ---------+------------+-------------------
> 1 | 1 | Baby Bob
> 100 | 100 | Jerry
>
>
​Try (not tested):​

​SELECT DISTINCT ON (main_id) main_id, sub_id, name
FROM names
ORDER BY main_id, sub_id ASC;

David J.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Peter Geoghegan 2016-10-26 20:20:17 Re: SERIALIZABLE and INSERTs with multiple VALUES
Previous Message Tim Smith 2016-10-26 16:22:33 Limiting to sub-id in a query ?