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 |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
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
From | Date | Subject | |
---|---|---|---|
Next Message | Iain | 2004-08-23 04:57:45 | Re: pg_dump/pg_restore question |
Previous Message | Greg Stark | 2004-08-23 03:52:01 | Re: sleep function |