Re: Aggregate over a linked list

From: Venky Kandaswamy <venky(at)adchemy(dot)com>
To: "pgsql-sql(at)postgresql(dot)org" <pgsql-sql(at)postgresql(dot)org>
Subject: Re: Aggregate over a linked list
Date: 2013-01-17 23:30:28
Message-ID: 776CCF725798BE4ABEC2521B9AEDBB35431A3055@BY2PRD0511MB429.namprd05.prod.outlook.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

Did you try:

select substring(contract from 1 for 1), min(entry_date), max(entry_date), sum(profit)
from contract_table
group by 1;

________________________________________

Venky Kandaswamy

Principal Engineer, Adchemy Inc.

925-200-7124

________________________________
From: pgsql-sql-owner(at)postgresql(dot)org [pgsql-sql-owner(at)postgresql(dot)org] on behalf of M Lubratt [mplubratt(at)gmail(dot)com]
Sent: Thursday, January 17, 2013 3:19 PM
To: pgsql-sql(at)postgresql(dot)org
Subject: [SQL] Aggregate over a linked list

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

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message wln 2013-01-20 03:35:54
Previous Message M Lubratt 2013-01-17 23:19:54 Aggregate over a linked list