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 |
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2007-12-04 : 10:31:47
|
| Hi, everyone,I could use a big help to get this one working. Pls see the sample data.I think I need a cursor to loop backwardly. Is there any other way?Thanks! USE tempdbgoIF Object_ID ('temdb..#myTable') is not NULL Drop Table #myTableCreate table #myTable (myID INT, myData INT, myDate DateTime)INSERT INTO #myTableSelect 1, 10, Getdate()-5 UNIONSelect 2, 12, Getdate()-4 UNIONSelect 3, 12, Getdate()-3 UNIONSelect 4, 15, Getdate()-2 UNIONSelect 5, 15, Getdate()-1 UNIONSelect 6, 15, Getdate()Here is the SELECT result I want to see.Current_Data, Last_diff_data, data_chg_date15, 12, 2007-12-01Note: don't worry about the time portion format.Please also tell me if your solution only apply to sql05. |
|
|
elancaster
A very urgent SQL Yakette
1208 Posts |
Posted - 2007-12-04 : 10:37:01
|
try this...select t2.mydata,t1.mydata,t1.mydatefrom #mytable t1 join #mytable t2 on t1.myid = t2.myid - 1 and t1.mydata <> t2.mydata and t1.mydate <> t2.mydate Em |
 |
|
|
elancaster
A very urgent SQL Yakette
1208 Posts |
Posted - 2007-12-04 : 10:39:20
|
or if you just wanted the most recent...select top 1 t2.mydata as current_data ,t1.mydata as last_diff_data ,t1.mydate as data_chg_datefrom #mytable t1 join #mytable t2 on t1.myid = t2.myid - 1 and t1.mydata <> t2.mydata and t1.mydate <> t2.mydateorder by t1.mydate desc Em |
 |
|
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-12-04 : 10:40:36
|
[code]DECLARE @MyTable TABLE (myID INT, myData INT, myDate DateTime)INSERT @myTableSELECT 1, 10, GETDATE() - 5 UNION ALLSELECT 2, 12, GETDATE() - 4 UNION ALLSELECT 3, 12, GETDATE() - 3 UNION ALLSELECT 4, 15, GETDATE() - 2 UNION ALLSELECT 5, 15, GETDATE() - 1 UNION ALLSELECT 6, 15, GETDATE()SELECT TOP 1 t1.myData AS Current_Data, t2.myData AS Last_Diff_Data, DATEADD(DAY, DATEDIFF(DAY, '19000101', t2.myDate), '19000101') AS Data_Chg_DateFROM @MyTable AS t1INNER JOIN @MyTable AS t2 ON t2.myDate < t1.MyDateWHERE t1.myData <> t2.myDataORDER BY t1.myDate DESC, t2.myDate DESC[/code] E 12°55'05.25"N 56°04'39.16" |
 |
|
|
Hommer
Aged Yak Warrior
808 Posts |
Posted - 2007-12-04 : 10:51:47
|
| Thank you for both of your quick replies.Peso's solution works!elancaster,Sorry my sample data is a little misleading. the myID in real data is not in a squence order, so t1.myid = t2.myid - 1 is not always true.Thanks a lot! You guys are great! |
 |
|
|
|
|
|
|
|