* How to Calculate the Difference between Each Value in a Certain Column and Its Previous One and Display Result in the Original Order in SQL?

We have table SAMPLE in the Sybase database. The data is as follows:

SECURITY_ID

DATE

REP

2256

2020-01-01

0

2257

2020-01-02

1

2258

2020-01-03

2

2256

2020-01-02

3

2256

2020-01-03

5

We are trying to calculate the difference of each REP value and its previous one and display values in the original order of the source table. Below is the desired result:

SECURITY_ID

DATE

REP

DIFF

2256

2020-01-01

0

0

2257

2020-01-02

1

1

2258

2020-01-03

2

2

2256

2020-01-02

3

3

2256

2020-01-03

5

2

In the original order, calculate the difference between REP on the current date and REP on the previous date for the same SECURITY_ID.

SQL written in Sybase:

SELECT SECURITY_ID, DATE, REP, REP - PREV_REP AS DIFF

FROM (

            SELECT T1.SECURITY_ID, T1.DATE, T1.REP

                        , COALESCE(T2.REP, 0) AS PREV_REP

            FROM SAMPLE T1

                        LEFT JOIN SAMPLE T2

                        ON T1.SECURITY_ID = T2.SECURITY_ID

                                    AND T2.DATE = T1.DATE - 1

)

ORDER BY REP;

The intuitive solution is simple. For records with same SECURITY_ID, subtract REP value in the previous records (with the previous date) from the current REP value. Since SQL is based on unordered sets, it needs to turn to window functions to achieve this. Coding will be complicated. For this task, the worst thing is that Sybase does not support window functions. We need to perform a self-join and then calculate the difference, generating even more complicated SQL.

 

Yet it is simple to achieve the algorithm in the open-source esProc SPL:

A

1

=connect("demo")

2

=A1.query@x("SELECT * FROM SAMPLE").derive(null:DIFF)

3

>A2.group(SECURITY_ID).(~.run(DIFF=REP-REP[-1]))

4

return A2

SPL gives a direct support for ordered sets, and is convenient for achieving calculations between neighboring values/rows/records.

Q & A Collection

https://stackoverflow.com/questions/64143908/difference-between-rows-of-the-same-column-if-particular-conditions-are-met