Re: get first and last row in one sql as two columns

From: "Dickson S(dot) Guedes" <listas(at)guedesoft(dot)net>
To: Tom Smith <tomsmith1989sk(at)gmail(dot)com>
Cc: PostgreSQL General <pgsql-general(at)postgresql(dot)org>
Subject: Re: get first and last row in one sql as two columns
Date: 2015-09-03 10:51:06
Message-ID: 20150903105106.GB6274@dba01
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Sep 02, 2015 at 07:14:40PM -0400, Tom Smith wrote:
> Hi:
>
> I need to get the first and last tow in one sql like below
>
> select first(col1), last(col1) from table order by col1

Have you tried the window functions [1] last_value and first_value?

You could use something like:

SELECT first_value(col1) over (order by col1),
last_value(col1) over (order by col1)
FROM table;

It should be as simple as that, or I miss your point.

[1] http://www.postgresql.org/docs/current/static/functions-window.html

[]s
--
Dickson S. Guedes
@guediz - http://github.com/guedes

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Tom Smith 2015-09-03 12:11:13 Re: get first and last row in one sql as two columns
Previous Message Martín Marqués 2015-09-03 10:20:48 Re: error on online backup using pg_basebackup tool