如何使用MATCH_RECOGNIZE获得所需的结果?

时间:2018-12-12 05:27:20

标签: sql oracle oracle12c match-recognize

输入:

enter image description here

使用MATCH_RECOGNIZE子句编写的查询

select *

from MTR_ACTIONS MATCH_RECOGNIZE (

     PARTITION BY METER_CODE

     ORDER BY ACTION_DT

     MEASURES 

     FIRST(ENTER.ACTION_DT) AS ENTER_DT,

     LAST(EX.ACTION_DT) AS EXIT_DT,

     MATCH_NUMBER() AS MN,

     CLASSIFIER() AS CLS

--     ALL ROWS PER MATCH 

--     ALL ROWS PER MATCH WITH UNMATCHED ROWS

    ONE ROW PER MATCH 

     AFTER MATCH SKIP PAST LAST ROW

     PATTERN (ENTER EX+)

     DEFINE

        ENTER AS (ENTER.ACTION='IN'),

        EX AS (EX.ACTION='OUT') 

     ) MR

WHERE  METER_CODE ='MTR1'

以上查询的输出:

enter image description here

所需的输出:

enter image description here

无论我在上述查询中的MEASURES / PATTERN / DEFINE部分中进行了什么更改,我都不知道为什么未填充EXIT_DT。

如何识别问题?

2 个答案:

答案 0 :(得分:0)

使用lead 分析函数可以解决您的问题

  select site, meter_code, enter_dt, exit_dt
    from
     (
      with mtr_actions( site, meter_code, action_date, action ) as
          (
           select 1,'MTR1',date'2012-03-21','IN'   from dual union all
           select 1,'MTR1',date'2012-04-24','READ' from dual union all
           select 1,'MTR1',date'2012-05-23','READ' from dual union all
           select 1,'MTR1',date'2016-05-27','OUT'  from dual union all
           select 2,'MTR1',date'2016-05-28','IN'   from dual union all
           select 1,'MTR1',date'2016-06-27','SKIP' from dual union all
           select 2,'MTR1',date'2016-06-27','READ' from dual union all
           select 2,'MTR1',date'2016-06-28','OUT'  from dual union all
           select 5,'MTR1',date'2016-06-29','IN'   from dual
          )
       select t.action, site, meter_code, action_date as enter_dt, 
              lead(t.action_date) over (order by t.action_date) as exit_dt
         from mtr_actions t
        where t.action in ('IN','OUT') 
      )  
    where action = 'IN';

    SITE    METER_CODE  ENTER_DT    EXIT_DT
    ------  ----------  ----------  ---------- 
      1        MTR1     21.03.2012  27.05.2016
      2        MTR1     28.05.2016  28.06.2016
      5        MTR1     29.06.2016  

Rextester Demo

答案 1 :(得分:0)

试试这个:

select * 
from MTR_ACTIONS 
MATCH_RECOGNIZE 
(     PARTITION BY METER_CODE
     ORDER BY action_date
     MEASURES 
     first(enter.site) as site,
     FIRST(ENTER.action_date) AS ENTER_DT,
     LAST(EX.action_date) AS EXIT_DT
     --MATCH_NUMBER() AS MN,
     --CLASSIFIER() AS CLS
     --ALL ROWS PER MATCH 
     --ALL ROWS PER MATCH --WITH UNMATCHED ROWS
     ONE ROW PER MATCH 
     --AFTER MATCH SKIP to next row
     PATTERN (ENTER X* EX?)
     DEFINE
        ENTER AS (ENTER.ACTION='IN'),
        x as  (action in ('READ','SKIP')),
        EX    AS (EX.ACTION='OUT') 
) MR
;