Re: ranked subqueries vs distinct question

From: Stephan Szabo <sszabo(at)megazone(dot)bigpanda(dot)com>
To: Karsten Hilbert <Karsten(dot)Hilbert(at)gmx(dot)net>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: ranked subqueries vs distinct question
Date: 2008-05-14 15:21:00
Message-ID: 20080514081932.V64034@megazone.bigpanda.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, 14 May 2008, Karsten Hilbert wrote:

> Modifying to:
>
> select * from (
>
> select distinct on (name) * from (
>
> select *, 1 as rank from dem.urb where
> name ilike 'Lei%' and
> zip = '04317'
>
> union all -- avoid distinctness at this level
>
> select *, 2 as rank from dem.urb where name ilike 'Lei%'
>
> ) as inner_union
>
> ) as unique_union
>
> order by rank, name;
>
> This works. However, one nuisance remains: Because the
> distinct happens before the order by rank it is happenstance
> whether rank 1 cities (with zip) will be listed on top
> anymore.

Can't you just do something like order by name, rank as part of the
distinct on subselect to force it to pick the rank 1 row for a given name?

So, basically
select * from
( select distinct on ... order by name, rank )
order by rank, name;

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message A B 2008-05-14 15:23:50 how to return parts of records from a function
Previous Message Karsten Hilbert 2008-05-14 14:56:45 Re: ranked subqueries vs distinct question