Is there any way to do a DATEDIFF / LEAD / LAG in SQL Server to calculate the difference between dates taking into account the previous / next record date.
SELECT
SELECT NUM, CLIENTE, EMISSAO
FROM PEDIDOS
WHERE CLIENTE = '06.028'
ORDER BY EMISSAO DESC
Result
NUM CLIENTE EMISSAO
35890H 06.028 20160226
y35888 06.028 20160225
y33449 06.028 20160122
y33046 06.028 20160111
y28763 06.028 20151125
AS9816 06.028 20151118
Expected Result:
ROW CODIGO EMISSAO TEMPO
1 06.028 20160226 5 -=> Utiliza o GETDATE() ou Deixa Zerado (0)
2 06.028 20141030 484 -=> Utiliza a data da linha 1
3 06.028 20141030 0 -=> Utiliza a data da linha 2
4 06.028 20140930 30 -=> Utiliza a data da linha 3
5 06.028 20140612 145 -=> Utiliza a data da linha 4
6 05.127 20160102 29 -=> Utiliza o GETDATE() ou Deixa Zerado (0)
7 05.127 20151225 9 -=> Utiliza a data da linha 6
8 05.127 20151205 20 -=> Utiliza a data da linha 7
Note: the ROW column is only for displaying the line that I am referencing in the description (- = >) next to it.
When changing the client, it stops using the date of the previous client and starts over again.