Question

Let's say I have a table of something like:

+-------+
| FIELD |
+-------+
| 1000  |
| 1200  |
| 1300  |
| 900   |
| 1400  |
+-------+

How can I perform SELECT query to retrieve rows 0..N, but instead of getting their values, get arithmetical difference with each row's previous row, i. e. RESULT(N) = ROW(N) - ROW(N-1) ? I expect to get something like:

+--------------+
| RESULT       |
+--------------+
| (EMPTY OR 0) |
| 200          |
| 100          |
| -400         |
| 500          |
+--------------+

I'm using DB2. It will be really cool if you provide me with some portable response that is not specific to a particular SQL DBMS.

Thanks in advance!

Was it helpful?

Solution

What you need is LAG function. it exists in multiple databases including

Syntax would be something like this

SELECT CASE WHEN LAG(MyField, 1) OVER ( PARTITION BY MyID ORDER BY SomeThing ) IS NULL THEN 0
            ELSE MyField - LAG(MyField, 1) OVER ( PARTITION BY MyID ORDER BY SomeThing )
       END AS Result
    FROM MyTable

Documentation on LAG from IBM

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top