Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
I have a table that contains 2 columns; receipt# and flag.Multiple rows may have the same receipt number.I need to select a row the the previous receipt has the flag set. The receipt numbers may not be contiguous.Sample:Receipt # Flag1 false1 true1 True3 False3 False4 false4 TrueExpected output3 False3 FalseThe receipt 3 rows are selected because there is a row with 1 as the receipt # and the flag setReceipt 1 rows are not selected because there is no previous receiptReceipt 4 rows are not selected because there are no receipt 3 rows with the flag setI have a solution that works in server 2005 but not 2000SELECT T.*FROM @Table AS TCROSS APPLY (SELECT MAX(col1) AS col1 FROM @Table AS A WHERE A.Col1 < T.Col1) AS ACROSS APPLY (SELECT MAX(col1) AS col1 FROM @Table AS B WHERE B.Col1 < T.Col1 AND B.Col2 = 'true') AS BWHERE A.col1 = B.col1
Lamprey
Master Smack Fu Yak Hacker
4614 Posts
Posted - 2010-04-22 : 17:36:20
You just need to change it around a bit:
SELECT col1, col2FROM ( SELECT T.*, (SELECT MAX(col1) AS col1 FROM @Table AS A WHERE A.Col1 < T.Col1) AS Acol1, (SELECT MAX(col1) AS col1 FROM @Table AS B WHERE B.Col1 < T.Col1 AND B.Col2 = 'true') AS BCol1 FROM @Table AS T ) AS DWHERE Acol1 = Bcol1
Movak
Starting Member
11 Posts
Posted - 2010-04-22 : 19:23:56
The requirements were changed on me a bit so here is the final question.It is similar to the one but instead of just one flag there are two and the criteria is that I want both transaction where one transaction has flag1 set and the next transaction has flag 2 set. There is also a register # that throws a wrench into it in that the transactions must be from the same register to be compared.ExampleR T F1 f22 1 1 02 1 1 01 2 0 01 3 1 01 3 0 12 4 0 11 5 0 11 5 0 01 6 0 1ResultR T F1 F22 1 1 02 1 1 01 3 1 01 3 0 12 4 0 11 5 0 11 5 0 0Transactions 1 and 4 are from the same register and are flag1 followed by flag 2Transactions 3 and 5 are from the same register and are flag1 followed by flag 2My brain hurts.