Aggregate over a linked list

From: M Lubratt <mplubratt(at)gmail(dot)com>
To: pgsql-sql(at)postgresql(dot)org
Subject: Aggregate over a linked list
Date: 2013-01-17 23:19:54
Message-ID: CANZYT4r4o__m6M7p_tPDRddY+1XiiB99n8t2zpeWuU2MCAYPKQ@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Hello!

I trade futures contracts and I have a PostgreSQL 9.2 database that keeps
track of all of my trading activity. The table includes columns for the
futures contract, the entry and exit dates and the profit for that
particular trade. Now, futures contracts expire, so within a trade being
indicated by my rules, I may need to "roll" contracts to the next contract
to avoid contract expiration. Therefore I can end up with multiple actual
trades in my table that are linked by the dates.

e.g.

If the contract is SH12 (S = soybeans and H12 = March 2012 expiration)

contract entry_date exit_date profit
-----------------------------------------------------------------------
SH12 2012-1-10 2012-2-27 500.00
SM12 2012-2-27 2012-3-30 200.00

While these are the actual exchange executed trades, I'd like to reduce
this into a single row like (linked by the "S" and then exit_date =
entry_date):

contract entry_date exit_date profit
-----------------------------------------------------------------------
S 2012-1-10 2012-3-30 700.00

I've gone round and round in my head, google, SQL Cookbook, etc. trying to
figure out how to do this. Can anyone provide any pointers on how to do
this?

Thanks and best regards!
Mark

Responses

Browse pgsql-sql by date

  From Date Subject
Next Message Venky Kandaswamy 2013-01-17 23:30:28 Re: Aggregate over a linked list
Previous Message Akihiro Okuno 2013-01-17 18:30:09 Re: number of values updated per column