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.
Hello everyone!Once again I try to analyze time series from the DAX (German Stock Exchange Index). My goal is to create a query that has a fourth column that shows the difference of the price in comparison to the price a second before.My table:select * from tbl order by sdatetime142 2008-03-25 09:04:36.000 6443.45163 2008-03-25 09:04:35.000 6443.48184 2008-03-25 09:04:34.000 6443.36As a result I wish to have something like:1 2008-03-25 09:04:36.000 6443.45 -0.32 2008-03-25 09:04:35.000 6443.48 0.123 2008-03-25 09:04:34.000 6443.36 ...... ....................... ....... .....I want it as one query without second table - at least not a permanent one.My approach which doesnt work is following:select t.id, t.Counter, t.sdatetime, t.price, t.price- (select row_number() over(order by sdatetime desc)as Counter, price from tbl) tt where tt.Counter = t.Counter+1from (select id, ROW_NUMBER() OVER(ORDER BY sdatetime desc) AS Counter,sdatetime, price from tbl) tMany thanks in advance and greetings from ViennaLandau
visakh16
Very Important crosS Applying yaK Herder
52326 Posts
Posted - 2008-08-29 : 05:12:44
[code]SELECT IDENTITY(int,1,1) AS Seq,* INTO #TempFROM tblorder by sdatetimeSELECT t1.*,t1.price-COALESCE(t2.price,0) AS diffFROM #Temp t1LEFT JOIN #Temp t2ON t2.Seq=t1.Seq+1[/code]