Skip site navigation (1) Skip section navigation (2)

Re: only last records in subgroups

From: Greg Stark <gsstark(at)mit(dot)edu>
To: Dino Vliet <dino_vliet(at)yahoo(dot)com>
Cc: pgsql-sql(at)postgresql(dot)org
Subject: Re: only last records in subgroups
Date: 2004-08-23 04:09:34
Message-ID: 878yc65wch.fsf@stark.xeocode.com (view raw or flat)
Thread:
Lists: pgsql-sql
Dino Vliet <dino_vliet(at)yahoo(dot)com> writes:

> x,0 and y,4 but how do I manage this in sql? I was
> hoping for a keyword LAST or so, where I can specify
> that when I've ordered my results with order by, I
> could only get the last of the subgroups (the first
> one is easy because I could use limit 1)

There's no concept of "first" and "last" in SQL outside of the ORDER BY clause
of your query. And you can easily reverse the order of the ORDER BY sort by
putting "DESC" after the columns you're sorting on.

But I don't understand how you intend to use "LIMIT 1" to solve your problem.
As you describe the problem you want the last (or first) record of *each*
*group*. Solving that using LIMIT would require a complex query with a
subquery in the column list which would be quite a pain.

As the other poster suggested, if you're just looking to fetch a single column
you can just use min() or max() to solve this. 

If you're looking to fetch more than one column Postgres provides a
non-standard SQL extension for dealing with this situation, "DISTINCT ON".

SELECT DISTINCT ON (id) id,day,other,columns FROM tab ORDER BY id,day

That gets the lowest value of "day". Using "ORDER BY id, day DESC" to get the
greatest value of "day".

-- 
greg


In response to

pgsql-sql by date

Next:From: IainDate: 2004-08-23 04:57:45
Subject: Re: pg_dump/pg_restore question
Previous:From: Greg StarkDate: 2004-08-23 03:52:01
Subject: Re: sleep function

Privacy Policy | About PostgreSQL
Copyright © 1996-2014 The PostgreSQL Global Development Group