mreiche / postgresql-first-last-aggregate

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

PostgreSQL first/last aggregate

This is a native PostgreSQL extension to support reading the first and last value of a group.

In comparison to partition's FIRST_VALUE() and LAST_VALUE() [1], it does only require groups.

The original snippet [2] has been modified to work with newer PostgreSQL versions.

Installation

Just run first_last_aggregegate.sql on your PostgreSQL console.

Example

select
    product,
    first(price) price_open,
    last(price) price_close,
    avg(price) price_avg,
    min(price) price_min,
    max(price) price_max
from products
    group by product
product price_open price_close price_avg price_min price_max
Affe 9.272449 67.55699 52.32810068130493 9.272449 83.53931
Kuh 87.33832 20.83148 61.10811456044515 20.83148 97.54616
Katze 51.7085 50.019222 38.3283109664917 9.954079 51.7085

Note: Data was generated by test/test-data.sql

References

About


Languages

Language:PLpgSQL 100.0%