Limits in subqueries...

From: Martijn van Oosterhout <kleptog(at)cupid(dot)suninternet(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: Limits in subqueries...
Date: 2000-06-21 14:16:24
Message-ID: 3950CE38.6816DC22@cupid.suninternet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I have a (simplified) table looking like:

serial int4
custid int4
stamp datetime

I want, for each customer, to get the serial of the the
highest timestamp for that customer, and for duplicate
timestamps, the highest serial. The way I thought how to
do that would be:

select custid, serial
from test b
where serial =
(select serial
from test a
where a.custid = b.custid
order by serial desc limit 1);

but thats not allowed. The best I could do is:

select custid, max(serial)
from test
where (custid,stamp) in
(select custid, max(stamp)
from test
group by custid)
group by custid;

Which is ugly and only works in this case because
max does what I want. It has a horrible plan though:

Aggregate (cost=1.36 rows=11 width=8)
-> Group (cost=1.36 rows=11 width=8)
-> Sort (cost=1.36 rows=11 width=8)
-> Seq Scan on test (cost=1.36 rows=11 width=8)
SubPlan
-> Aggregate (cost=1.36 rows=11 width=12)
-> Group (cost=1.36 rows=11 width=12)
-> Sort (cost=1.36 rows=11 width=12)
-> Seq Scan on test (cost=1.36
rows=11 width=12)

In the more general case, this won't work.

Is there a better way of doing this? Does postgres 7.0 do
better in this case?
--
Martijn van Oosterhout <kleptog(at)cupid(dot)suninternet(dot)com>
http://cupid.suninternet.com/~kleptog/

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Sevo Stille 2000-06-21 14:19:29 Re: Help:How do you find that how much storage is taken by the database??
Previous Message Bryan White 2000-06-21 14:12:03 table contraints and pg_dump