Re: using window-functions to get freshest value - how?

From: silly8888 <silly8888(at)gmail(dot)com>
To: "Massa, Harald Armin" <chef(at)ghum(dot)de>
Cc: depesz(at)depesz(dot)com, pgsql-general(at)postgresql(dot)org
Subject: Re: using window-functions to get freshest value - how?
Date: 2009-11-20 12:18:22
Message-ID: 3c8f9f940911200418q63e46754oc83a0a0ba3a285@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

> and how would I use DISTINCT ON for this query? Please bear in mind,
> that there is more then one id_bf (just stopped the sample data with
> one of them)

I posted the answer more than hour ago:

SELECT DISTINCT ON (id_rf) * FROM rfmitzeit ORDER BY id_rf,
letztespeicherung DESC;

The equivalent with window functions would be:

SELECT * FROM (SELECT *,row_number() OVER (PARTITION BY id_rf ORDER BY
letztespeicherung DESC) FROM rfmitzeit) t WHERE row_number=1

If you check the query plan you will understand why DISTINCT ON is the
best option. Essensially, DISTINCT ON has no additional cost other the
cost of

ORDER BY id_rf, letztespeicherung DESC

which is unavoidable

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Thom Brown 2009-11-20 12:22:07 Re: using window-functions to get freshest value - how?
Previous Message Sam Jas 2009-11-20 12:18:14 Re: Strange performance degradation