question

asheeshagnihotri02314 avatar image
asheeshagnihotri02314 asked

I want to compare row to row for each ID in SQL query

I have a table which contains two columns Id and date column where there are multiple rows for each IDs. For example ID 2034 is repeating 4 times and ID 2345 is repeating 6 times, now for each ID, I need to create days_diff column where i want to compare first row date with second row date then first row date with third row date and when the difference is greater than 21 days then compare next row date with previous row date instead of first row date.

Final Data should be like this:

ID Date days_diff

2034 2022-01-01 -

2034 2022-01-18 17

2034 2022-01-24 23

2034 2022-01-26 02

2035 2022-02-01 -

2035 2022-02-13 12

2035 2022-03-13 28

2035 2022-03-16 03

mysqlplsqlsqlquery
2 comments
10 |1200

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.

asheeshagnihotri02314 avatar image asheeshagnihotri02314 commented ·

-, 17, 23, 02,- , 12, 28, 03 are days difference values i needed in my final dataset.

0 Likes 0 ·
Jeff Moden avatar image Jeff Moden commented ·
What version of SQL Server are you using? It's important because there are two different methods for doing this in a Set-Based manner and they are version dependent.



0 Likes 0 ·

0 Answers

·

Write an Answer

Hint: Notify or tag a user in this post by typing @username.

Up to 2 attachments (including images) can be used with a maximum of 512.0 KiB each and 1.0 MiB total.