문제

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!

도움이 되었습니까?

해결책

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top