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 |
|
JeanneZhang
Starting Member
5 Posts |
Posted - 2008-01-09 : 14:16:59
|
| I need to have a SQL to catch the flag changes based on the ID. The table data like:ID Update_Date Flag100 12/03/2007 Y100 12/05/2007 Y100 12/09/2007 N100 12/10/2007 N100 12/19/2007 Y101 12/03/2007 N101 12/09/2007 Y101 12/21/2007 Y102 12/07/2007 Y102 12/18/2007 Y102 12/24/2007 N102 12/28/2007 NThe result should be:ID Update_Date Flag100 12/09/2007 N100 12/19/2007 Y101 12/09/2007 Y102 12/24/2007 NThanks a lot for any help.Jeanne |
|
|
jdaman
Constraint Violating Yak Guru
354 Posts |
Posted - 2008-01-09 : 15:20:26
|
| declare @t table ( ID int, Update_Date datetime, Flag char(1) )insert @t ( ID, Update_Date, Flag )select 100, '12/03/2007', 'Y' union allselect 100, '12/05/2007', 'Y' union allselect 100, '12/09/2007', 'N' union allselect 100, '12/10/2007', 'N' union allselect 100, '12/19/2007', 'Y' union allselect 101, '12/03/2007', 'N' union allselect 101, '12/09/2007', 'Y' union allselect 101, '12/21/2007', 'Y' union allselect 102, '12/07/2007', 'Y' union allselect 102, '12/18/2007', 'Y' union allselect 102, '12/24/2007', 'N' union allselect 102, '12/28/2007', 'N'select t2.ID, t2.Update_Date, t2.Flagfrom ( select row_number() over(partition by ID order by Update_Date) rownum, * from @t ) t1join ( select row_number() over(partition by ID order by Update_Date) rownum, * from @t ) t2 on t1.ID = t2.ID and t1.rownum + 1 = t2.rownumwhere t1.Flag <> t2.Flag |
 |
|
|
|
|
|
|
|