Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
AskSQLTeam
Ask SQLTeam Question
0 Posts |
Posted - 2005-08-10 : 07:44:29
|
| Mike writes "I am needing to write a query to find the maximum sequential occurances of a record with a certain value. For example, I have a bank account, account #1. I need to find the maximum number of sequential transactions (in order of DateTimeofTransaction) where the balance has been left negative (Ending Balance). In the example below, I will have 2 as the maximum number of sequential transactions that left the ending balance 0.I have been able to do this in a cursor - but haven't figured out how to do this in a query. I cannot use a cursor because I am working with hundreds of thousands of records. Any help you can provide would be greatly appreciated!Account# DateTimeofTransaction Ending Balance1 7/1/2005 10:00am 25.221 7/1/2005 11:00am 10.191 7/1/2005 1:00pm -22.251 7/2/2005 9:00am -31.221 7/3/2005 10:00am 19.221 7/4/2005 11:00am -10.111 7/5/2005 12:00pm 15.00" |
|
|
Seventhnight
Master Smack Fu Yak Hacker
2878 Posts |
Posted - 2005-08-10 : 08:38:07
|
[code]Declare @myTable table (acct int, tranDate datetime, bal money)Insert Into @myTableSelect 1, '7/1/2005 10:00am', 25.22 Union AllSelect 1, '7/1/2005 11:00am', 10.19 Union AllSelect 1, '7/1/2005 1:00pm', -22.25 Union AllSelect 1, '7/2/2005 9:00am', -31.22 Union AllSelect 1, '7/3/2005 10:00am', 19.22 Union AllSelect 1, '7/4/2005 11:00am', -10.11 Union AllSelect 1, '7/5/2005 12:00pm', 15.00Select * From @myTableSelect runEnding = nextPos, count(*) From ( Select A.acct, A.tranDate, A.bal, nextPos = (Select min(tranDate) From @myTable Where acct = A.acct and tranDate > A.tranDate and bal>0) From @myTable A Where bal<0 ) ZGroup By nextPosSelect acct, maxRun = max(cnt)From ( Select acct, runEnding = nextPos, cnt = count(*) From ( Select A.acct, A.tranDate, A.bal, nextPos = (Select min(tranDate) From @myTable Where acct = A.acct and tranDate > A.tranDate and bal>0) From @myTable A Where bal<0 ) Z Group By acct, nextPos ) AGroup By acct[/code]Corey Co-worker on The Wizard of Oz "...those three midgets that came out and danced, the freaked me out when I was little. But they are ok now." |
 |
|
|
|
|
|
|
|