2

I hope someone can help. I have a table that looks like the following.

ModifyDate| ModifiedBy | TaskID |
2018-02-05| Bob        | 55444  |
2018-02-06| Lily       | 55444  |
2018-02-08| Sarah      | 55444  |

For each row I need to calculate the time difference in days between Modifydate for each TaskID.

For example my output should look like the below:

ModifyDate| ModifiedBy | TaskID | Time
2018-02-05| Bob        | 55444  |  1
2018-02-06| Lily       | 55444  |  2
2018-02-08| Sarah      | 55444  | NULL

There is a NULL on Sarah as she was the last person to modify the Task.

Does this make sense? Hopefully someone can help

Thanks!

Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98
Jess8766
  • 377
  • 5
  • 16

1 Answers1

4

Something like this should work:

SELECT ModifyDate, ModifiedBy, TaskID,
       DATEDIFF(DAY, ModifyDate,
                     LEAD(ModifyDate) OVER (PARTITION BY TaskID  
                                            ORDER BY ModifyDate))
FROM mytable

Demo here

Giorgos Betsos
  • 71,379
  • 9
  • 63
  • 98