简体   繁体   中英

ORACLE SQL: Subtract dates of two or more consecutive rows

I would like to subtract dates of two consecutive rows, using ORACLE's LAG-function (ORACLE version 19g):

SELECT CLIENT, ID, GROUP_A, GROUP_B, GROUP_C, DATE_A, DATE_B
       (DATE_A - LAG(DATE_B, 1) OVER (PARTITION BY GROUP_A, ID 
                                          ORDER BY ID ASC, GROUP_A ASC, GROUP_B ASC)) AS DELTA_TIME_IN_DAYS
  FROM MY_TABLE

在此处输入图片说明

As you can see, the problem is, that there can be multiple entries like in line 3 and 4. Of course column "DELTA_TIME_IN_DAYS" entry in line 4 shouldn't be negative. It should be "1" as result.

Do you have any suggestions to solve this problem?

I think you want to order by date_b , if you want non-negative numbers:

SELECT CLIENT, ID, GROUP_A, GROUP_B, GROUP_C, DATE_A, DATE_B
       (DATE_A - LAG(DATE_B, 1) OVER (PARTITION BY GROUP_A, ID 
                                      ORDER BY ID DATE_B ASC
                                     )
        ) AS DELTA_TIME_IN_DAYS
FROM MY_TABLE;

Note that you do not need to repeat the partitioning keys in the ORDER BY .

You may use range between to offset by groups of rows with identical sort ordinal rather than by physical rows like lag do by default. So, let's use last_value with offset of 1 group to do the same that lag does.

with a (id, start_dt, end_dt) as (
  select 1, date '2021-01-01', date '2021-01-31' from dual union all
  select 2, date '2021-02-01', date '2021-02-27' from dual union all
  select 3, date '2021-03-01', date '2021-03-25' from dual union all
  select 3, date '2021-03-01', date '2021-03-25' from dual union all
  select 4, date '2021-04-01', date '2021-05-31' from dual union all
  select 4, date '2021-04-01', date '2021-05-31' from dual
)
select
  a.*
  , last_value(end_dt) over(order by id asc range between unbounded preceding and 1 preceding) as dt_diff
from a
D START_DT END_DT DT_DIFF
1 2021-01-01T00:00:00Z 2021-01-31T00:00:00Z (null)
2 2021-02-01T00:00:00Z 2021-02-27T00:00:00Z 2021-01-31T00:00:00Z
3 2021-03-01T00:00:00Z 2021-03-25T00:00:00Z 2021-02-27T00:00:00Z
3 2021-03-01T00:00:00Z 2021-03-25T00:00:00Z 2021-02-27T00:00:00Z
4 2021-04-01T00:00:00Z 2021-05-31T00:00:00Z 2021-03-25T00:00:00Z
4 2021-04-01T00:00:00Z 2021-05-31T00:00:00Z 2021-03-25T00:00:00Z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM