我有一个要求的人。我想知道这个循环是否发生。我不知道从哪里开始。 表格中包含这样的列
Issue_no old_value new value
1 a b
1 b c
1 c d
1 d a
我想找到是否在旧的值d之后它是否转到a。循环必须像这样a到b,b到c,c到d。但我想知道d是否发生了谁能知道如何找到它?
答案 0 :(得分:1)
这将在您的数据中查找周期:
Oracle 11g R2架构设置:
CREATE TABLE Test (Issue_no, old_value, new_value ) AS
SELECT 1, 'a', 'b' FROM DUAL
UNION ALL SELECT 1, 'b', 'c' FROM DUAL
UNION ALL SELECT 1, 'c', 'd' FROM DUAL
UNION ALL SELECT 1, 'd', 'a' FROM DUAL
UNION ALL SELECT 2, 'a', 'b' FROM DUAL
UNION ALL SELECT 2, 'b', 'c' FROM DUAL
UNION ALL SELECT 2, 'c', 'd' FROM DUAL
UNION ALL SELECT 2, 'd', 'e' FROM DUAL
UNION ALL SELECT 3, 'a', 'b' FROM DUAL
UNION ALL SELECT 3, 'b', 'a' FROM DUAL;
查询1 - 如果您只想列出所有周期:
SELECT Issue_no,
CONNECT_BY_ROOT old_value || SYS_CONNECT_BY_PATH( new_value, '-' ) AS cyclic_path
FROM TEST t
WHERE CONNECT_BY_ISCYCLE = 1
START WITH
old_value = 'a'
CONNECT BY
NOCYCLE
PRIOR issue_no = issue_no
AND PRIOR new_value = old_value
<强> Results 强>:
| ISSUE_NO | CYCLIC_PATH |
|----------|-------------|
| 1 | a-b-c-d-a |
| 3 | a-b-a |
查询2 - 如果您想查找特定周期a-b-c-d-a
:
SELECT Issue_no
FROM (
SELECT Issue_no,
CONNECT_BY_ROOT old_value || SYS_CONNECT_BY_PATH( new_value, '-' ) AS cyclic_path
FROM TEST t
WHERE CONNECT_BY_ISCYCLE = 1
START WITH
old_value = 'a'
CONNECT BY
NOCYCLE
PRIOR issue_no = issue_no
AND PRIOR new_value = old_value
)
WHERE cyclic_path = 'a-b-c-d-a'
<强> Results 强>:
| ISSUE_NO |
|----------|
| 1 |