-1

I have to calculate the weight difference of the given dataset based on the previous row of each group ids.

For instance:

ID  Wt
1   60.5
1   58 
1   62
2   89
2   75
2   72

Expected Result:

ID  Wt    diff
1   60.5  2.5
1   58    -4
1   62     
2   89    14
2   75    3
2   72

Kindly suggest code to solve the problem. Thanks in advance

Dale K
  • 25,246
  • 15
  • 42
  • 71
Jammy
  • 33
  • 6
  • 1
    It is easy but you first need to explain what determines if one row is previous to the other. What determines that 58 comes before 52 but after 60.5 – Salman A Sep 09 '21 at 09:27
  • Does this answer your question? [Is there a way to access the "previous row" value in a SELECT statement?](https://stackoverflow.com/questions/710212/is-there-a-way-to-access-the-previous-row-value-in-a-select-statement) – Thom A Sep 09 '21 at 09:28
  • Actually, I sorted the dataset by ID and Date column then I calculate the code you suggest. – Jammy Sep 09 '21 at 09:29
  • use LEAD() function – Rahul Biswas Sep 09 '21 at 09:37

1 Answers1

0

there are analytics functions for this in SQL the names are Lag for previous row and lead for nest row

for your example

select ID,Wd, Wd - lead(Wd) over(partition by ID order by {insert ordar by column name{date}) as diff from table_name 

see https://learn.microsoft.com/en-us/sql/t-sql/functions/lead-transact-sql?view=sql-server-ver15

gal peled
  • 467
  • 5
  • 8