Teradata中的递归脚本

时间:2018-07-31 14:49:46

标签: recursive-query teradata-sql-assistant

我在Teradata中有一个表,由以下五列组成:

Old   New   Type_of_Old    Type_of_New    Change_Dt
----------------------------------------------------
A     B         0             1            Date 1
B     C         1             1            Date 2
C     D         1             0            Date 3
D     B         0             1            Date 4
B     E         1             1            Date 5

我想绑定旧的-从第一个其type_of_old = 0的元素开始的新值,并在到达最后一个type_of_old = 1时切开边界。最后,我想获得此数据:

Fırst    Next       Change Dt
-------------------------------
A        B          Date 1
A        C          Date 2
A        D          Date 3
D        B          Date 4
D        E          Date 5

问题是,元素B是A和D的下一个元素,它们的更改日期不同。因此,当我使用WITH RECURSIVE脚本时,它将绑定B的下一个元素,并且两个A都以D结尾。

到目前为止,我已经编写了此脚本,但是当它达到type_of_old = 1时,我无法设法削减界限

CREATE MULTISET TABLE TEST.TABLE_A ( OLD_ELM VARCHAR(1), NEW_ELM VARCHAR(1), 
TYPE_OF_OLD BYTEINT , TYPE_OF_NEW BYTEINT, CHANGE_DT DATE)

INSERT INTO TEST.TABLE_A ('A','B',0, 1, DATE '2018-01-01');
INSERT INTO TEST.TABLE_A ('B','C',1, 1, DATE '2018-02-01');
INSERT INTO TEST.TABLE_A ('C','D',1, 0, DATE '2018-03-01');
INSERT INTO TEST.TABLE_A ('D','B',0, 1, DATE '2018-04-01');
INSERT INTO TEST.TABLE_A ('B','E',1, 1, DATE '2018-05-01');

WITH RECURSIVE ELEMENT_PATH ( FIRST_ELM, NEXT_ELM, CHANGE_DT ) AS 
( SELECT OLD_ELM, NEW_ELM, CHANGE_DT
   FROM TEST.TABLE_A
  WHERE TYPE_OF_OLD = 0
    AND TYPE_OF_NEW = 1

  UNION ALL

 SELECT P.FIRST_ELM, A.NEW_ELM, A.CHANGE_DT
   FROM ELEMENT_PATH P
   JOIN TEST.TABLE_A A ON A.OLD_ELM = P.NEXT_ELM
  WHERE A.CHANGE_DT > P.CHANGE_DT) 
 SELECT * FROM ELEMENT_PATH

此脚本中的数据如下:

FIRST_ELM   NEXT_ELM    CHANGE_DT
   A           B        01.01.2018
   A           C        01.02.2018
   A           D        01.03.2018
   D           B        01.04.2018
   D           E        01.05.2018
   A           B        01.04.2018 (Wrong)
   A           E        01.05.2018 (Wrong)
   A           E        01.05.2018 (Wrong)

我该如何解决?

预先感谢

致谢

1 个答案:

答案 0 :(得分:0)

您需要在where子句中添加一个附加条件(AND TYPE_OF_OLD <> 0)以删除错误的记录。

WITH RECURSIVE ELEMENT_PATH ( FIRST_ELM, NEXT_ELM, CHANGE_DT ) AS 
( SELECT OLD_ELM, NEW_ELM, CHANGE_DT
   FROM DQRC.TABLE_A
  WHERE TYPE_OF_OLD = 0
    AND TYPE_OF_NEW = 1

  UNION ALL

 SELECT P.FIRST_ELM, A.NEW_ELM, A.CHANGE_DT
   FROM ELEMENT_PATH P
   JOIN DQRC.TABLE_A A 
   ON A.OLD_ELM = P.NEXT_ELM
  WHERE A.CHANGE_DT > P.CHANGE_DT
  AND TYPE_OF_OLD <> 0) 
 SELECT * FROM ELEMENT_PATH

不确定,因为我今天刚刚看过,它现在对您有用。