Re: only last records in subgroups - Mailing list pgsql-sql

From Greg Stark
Subject Re: only last records in subgroups
Date
Msg-id 878yc65wch.fsf@stark.xeocode.com
Whole thread Raw
In response to only last records in subgroups  (Dino Vliet <dino_vliet@yahoo.com>)
List pgsql-sql
Dino Vliet <dino_vliet@yahoo.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



pgsql-sql by date:

Previous
From: Greg Stark
Date:
Subject: Re: sleep function
Next
From: "Iain"
Date:
Subject: Re: pg_dump/pg_restore question