Calculating differences between two rows for access sql query -


i trying create query new column containing differences between row n , row n+1 column x table 1.


table 1

sample_id: 1, 2, 3, 4, 5

x: 42060, 42069, 42069, 42111, 42132


query 1 (ideal result)

sample_id: 1, 2, 3, 4, 5

diff: 0, 9, 0, 42, 21


i used following sql.

select [table1].sample_id,[table1].x - prev.x diff [table1] inner join [table1] prev on [table1].sample_id -1 = prev.sample_id [table1].sample_id > 1 

however, omits first row; thus, instead of getting result presented above query 1, following.


results

sample_id: 2, 3, 4, 5

diff: 9, 0, 42, 21


how can retain first row (sample_id=1) 0 value?

try this

select [table1].sample_id,[table1].x - prev.x diff   [table1]         inner join [table1] prev on [table1].sample_id -1 = prev.sample_id  [table1].sample_id >= 1 

which pick rows have sampleid greater or equal 1, or

select [table1].sample_id,[table1].x - prev.x diff   [table1]         inner join [table1] prev on [table1].sample_id -1 = prev.sample_id  [table1].sample_id not null 

which pick rows have sampleid


Comments

Popular posts from this blog

apache - PHP Soap issue while content length is larger -

asynchronous - Python asyncio task got bad yield -

javascript - Complete OpenIDConnect auth when requesting via Ajax -