tags:

views:

28

answers:

1

I have the following situation. I have a database of transactions about multiple contracts. I am looking for the first transaction where alpha < alphaBound and the contract has a future, meaning there are records after the date for the same contract ID. To do this, I have been doing:

select transactionID, 
       date, 
       alpha, 
       contractID 
  from myDB 
 where date >= '2000-01-01' 
   and alpha < alphaBound

and then iterating over the results as follows

for(i in 1:length(resultSet) ) {
  date.tmp = resultSet[i, date]
  contractID.tmp = resultSet[i, contractID]

  future = doQuery("select * from myDB where date > " + date.tmp + " AND contractID = " + contractID.tmp)

  if(future is not empty) {
      # break! Found the entry I wanted
  }

}

How can I do this in 1 query? Thanks.

+3  A: 

Use:

SELECT t.transactionid,
       t.date,
       t.alpha,
       t.contractid
  FROM mydb t
 WHERE t.date >= '2000-01-01' 
   AND t.alpha < alphaBound
   AND EXISTS(SELECT NULL
                FROM mydb x
               WHERE x.contractid = t.contractid
                 AND x.date > t.date)
OMG Ponies
Thanks for the query.
stevejb