我有一张桌子:
表1
tran_id user_id start_date end_date
1 100 01-06-2018 18-06-2018
2 100 14-06-2018 14-06-2018
4 100 19-07-2018 19-07-2018
7 101 05-01-2018 06-01-2018
9 101 08-01-2018 08-01-2018
3 101 03-01-2018 03-01-2018
演示-Link
这是逻辑:
我需要找到两个trans_id
之间的日期差,该成员按start_date排序,而start_date和end_date没有重叠。
我们需要检查用户一次处理一条记录的最大终止日期。
逻辑将是:
对于成员:
user_id
和start_date
排序所有记录trans_id
= 1,end_date
= 18-06-2018
,设置max_end_date
= 18-06-2018 trans_id
= 2,end_date
= 14-06-2018,end_date
<max_end_date
,继续前进trans_id
= 3,end_date
= 19-07-2018,end_date
> max_end_date
,在输出中添加一条记录,其中
transidfrom
= 1(因为这是max_end_date
的记录)transidto
= 4(因为这是end_date
> max_end_date
的记录)transidfrom_end_date
= 18-06-2018,从end_date
的{{1}}中选择trans_id
transidfrom
= 19-07-2018,从transidto_start_date
的{{1}}中选择start_date
trans_id
= transidto
-datediff
输出如下:
table2
transidto_start_date
在Oracle SQL中有1种查询方法吗?
答案 0 :(得分:1)
如果我正确理解了您的要求,那么也许可以做到:
FSITJA@db01 2019-07-08 12:08:59> with table1(tran_id, user_id, start_date, end_date) as (
2 select 1, 100, date '2018-06-01', date '2018-06-18' from dual union all
3 select 2, 100, date '2018-06-14', date '2018-06-14' from dual union all
4 select 4, 100, date '2018-07-19', date '2018-07-19' from dual union all
5 select 7, 101, date '2018-01-05', date '2018-01-06' from dual union all
6 select 9, 101, date '2018-01-08', date '2018-01-08' from dual union all
7 select 3, 101, date '2018-01-03', date '2018-01-03' from dual )
8 select rownum as my_id,
9 tran_id as transidfrom,
10 next_tran_id as transidto,
11 end_date as transidfrom_end_date,
12 next_end_date as transidto_start_date,
13 datediff
14 from (select tran_id,
15 user_id,
16 start_date,
17 end_date,
18 lead(tran_id) over (partition by user_id order by end_date) next_tran_id,
19 lead(start_date) over (partition by user_id order by end_date) next_end_date,
20 lead(start_date) over (partition by user_id order by end_date) - end_date datediff
21 from table1)
22 where datediff > 0;
MY_ID TRANSIDFROM TRANSIDTO TRANSIDFROM_END_DAT TRANSIDTO_START_DAT DATEDIFF
---------- ----------- ---------- ------------------- ------------------- ----------
1 1 4 2018-06-18 00:00:00 2018-07-19 00:00:00 31
2 3 7 2018-01-03 00:00:00 2018-01-05 00:00:00 2
3 7 9 2018-01-06 00:00:00 2018-01-08 00:00:00 2
3 rows selected.