如何在Oracle中检查递归模式数据?

时间:2019-07-16 20:41:21

标签: sql oracle

假设我输入的数据如下:

ID Column
-------------------
101
101UK
101IN
1002
1002AU
1002US
MARA

Output
ID Column
---------------
101
1002
MARA

第1行数据pattern101在第2行和第3行重复,因此在输出中我只需要第1行。类似于第4行。由于第5行仅出现一次,因此将按原样在输出中显示

预先感谢

2 个答案:

答案 0 :(得分:1)

Oracle设置

CREATE TABLE table_name ( ID ) AS
SELECT '101' FROM DUAL UNION ALL
SELECT '101UK' FROM DUAL UNION ALL
SELECT '101IN' FROM DUAL UNION ALL
SELECT '1002' FROM DUAL UNION ALL
SELECT '1002AU' FROM DUAL UNION ALL
SELECT '1002US' FROM DUAL UNION ALL
SELECT 'MARA' FROM DUAL

查询1

SELECT *
FROM   table_name t
WHERE  NOT EXISTS (
  SELECT 1
  FROM   table_name m
  WHERE  t.id LIKE m.id || '%'
  AND    t.id > m.id
)

查询2

SELECT DISTINCT id
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY
       PRIOR id LIKE id || '%'
AND    PRIOR id > id

输出

两者输出相同。

| ID   |
| :--- |
| MARA |
| 101  |
| 1002 |

db <>提琴here

答案 1 :(得分:0)

具有模式识别功能:

select strt_id as id
  from sample_table
  match_recognize (
    order by id
    measures first(strt.id) as strt_id,
             classifier() as classif
    one row per match
    after match skip past last row
    pattern (strt same*)
    define 
    same as instr(same.id, prev(strt.id)) <> 0
  ) m
  where classif = 'STRT'
  order by id;

示例执行:

FSITJA@db01 2019-07-16 17:39:25> select strt_id as id
  2    from sample_table
  3    match_recognize (
  4      order by id
  5      measures first(strt.id) as strt_id,
  6               classifier() as classif
  7      one row per match
  8      after match skip past last row
  9      pattern (strt same*)
 10      define
 11      same as instr(same.id, prev(strt.id)) <> 0
 12    ) m
 13    where classif = 'STRT'
 14    order by id;

ID
------
1002
101
MARA