Oracle数据库中物料因果事件的查询

dldeef67  于 2023-10-16  发布在  Oracle
关注(0)|答案(2)|浏览(106)

我有一个Oracle表(Oracle数据库v12.2.0.2.1),它记录了一个项目何时有一个保护(PROT)放置在它上面,以及它的后续保护删除(RMPR)。
规则是,一个项目不应该连续保护两次。换句话说,在可以对物品放置第二个保护之前,需要首先移除前一个。
数据库的用户并不总是遵循此规则,并且在删除前一项之前无意中对项进行了保护。我想审计该表并查询同一项上的连续“PROT”。以下是我的数据示例:

  • 项目ID是项目的唯一标识符
  • 事件ID是PROT或RMPR事件的唯一标识符
  • EVENT_TYPE是事件的类型(PROT或RMPR)

| TENURE_NUMBER_ID|事件编号|事件类型|
| --|--|--|
| 1099391 | 5994168 |RMPR|
| 1099391 | 5994169 |PROT|
| 1099489 | 5963896 |PROT|
| 1099489 | 5994168 |RMPR|
| 1099489 | 5994169 |PROT|
| 1099491 | 5963896 |PROT|
| 1099491 | 5994168 |RMPR|
| 1099491 | 5994169 |PROT|
| 1099491 | 5990993 |PROT|
| 1099491 | 5983849 |RMPR|
| 1099967 | 5989988 |PROT|
| 1099967 | 5989990 |PROT|
| 1099967 | 5989992 |RMPR|
| 1099967 | 5989993 |PROT|
| 1099967 | 5989999 |PROT|

eoigrqb6

eoigrqb61#

with t(TENURE_NUMBER_ID, EVENT_NUMBER, EVENT_TYPE) as (
  select 1099391, 5994168, 'RMPR' from dual union all
  select 1099391, 5994169, 'PROT' from dual union all
  select 1099489, 5963896, 'PROT' from dual union all
  select 1099489, 5994168, 'RMPR' from dual union all
  select 1099489, 5994169, 'PROT' from dual union all
  select 1099491, 5963896, 'PROT' from dual union all
  select 1099491, 5994168, 'RMPR' from dual union all
  select 1099491, 5994169, 'PROT' from dual union all
  select 1099491, 5990993, 'PROT' from dual union all
  select 1099491, 5983849, 'RMPR' from dual union all
  select 1099967, 5989988, 'PROT' from dual union all
  select 1099967, 5989990, 'PROT' from dual union all
  select 1099967, 5989992, 'RMPR' from dual union all
  select 1099967, 5989993, 'PROT' from dual union all
  select 1099967, 5989999, 'PROT' from dual
)
select *
from t
  match_recognize (
     partition by TENURE_NUMBER_ID
     order by EVENT_NUMBER
     measures 
        count(same.*) as cnt
       ,CLASSIFIER() AS pttrn
     all rows per match
     pattern( (same|diff)*)
     define
       same as prev(EVENT_TYPE) = EVENT_TYPE
      ,diff as lnnvl(prev(EVENT_TYPE) = EVENT_TYPE)
  )

DBFiddle:https://dbfiddle.uk/f4MqsPWX

sczxawaw

sczxawaw2#

您还可以使用

last_value(EVENT_TYPE) over(PARTITION BY TENURE_NUMBER_ID ORDER BY EVENT_NUMBER
            ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) AS last_event_type

的行

where last_event_type = event_type

是重复的,所以在last_event_type = 'PROT'上也进行过滤将给予答案。

相关问题