这里是你如何能在甲骨文12.1及以上的做到这一点。
由于每个entity_id
只有一行type = 'A'
,因此MATCH_RECOGNIZE
中的排序保证我们计算所需的行将成为每个分区中的前三行。这意味着不需要DEFINE
子句;但语法要求它(这就是为什么它只是要求0 = 0
)。
with
test_data (created_date, entity_id, tp) as (
select to_date('02-MAY-17', 'dd-MON-rr'), 1234, 'A' from dual union all
select to_date('03-MAY-17', 'dd-MON-rr'), 1234, 'B' from dual union all
select to_date('04-MAY-17', 'dd-MON-rr'), 1234, 'B' from dual union all
select to_date('05-MAY-17', 'dd-MON-rr'), 1234, 'B' from dual
)
-- End of test data (not part of the solution). SQL query begins below this line
select entity_id, diff_between_a_b1, diff_between_a_b2
from test_data
match_recognize (
partition by entity_id
order by tp, created_date
measures b1.created_date - a.created_date as diff_between_a_b1,
b2.created_date - a.created_date as diff_between_a_b2
pattern (^ a b1 b2)
define a as 0 = 0
)
;
ENTITY_ID DIFF_BETWEEN_A_B1 DIFF_BETWEEN_A_B2
--------- ----------------- -----------------
1234 1 2
什么是Oracle版本? – mathguy