我需要创建一个teradata宏,以便首先将信息提取到易失性表中,然后执行CTE从该易失性表中提取数据并将其插入到teradata表中,尝试了各种方法都失败了,谢谢帮助!
CREATE MACRO database.macro_insertion_tablename AS (
CREATE VOLATILE TABLE vt AS
(
SELECT
id, bu,
CONCAT(TO_CHAR(comment_date, 'yyyy-mm-dd HH24:MI:SS'), ' ', action) AS full_action,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) AS row_num,
COUNT(*) OVER (PARTITION BY id) as cnt
FROM database.table1
) WITH DATA UNIQUE PRIMARY INDEX(id, row_num) ON COMMIT PRESERVE ROWS;
WITH RECURSIVE cte (id, bu, act, rn) AS
(
SELECT
id, bu
,CAST(full_action AS VARCHAR(5000)) AS full_action
,row_num
FROM vt
WHERE row_num = cnt
UNION ALL
SELECT
vt.id, vt.bu
,cte.act || ' / ' || vt.full_action
,vt.row_num
FROM vt
JOIN cte On vt.id = cte.id AND vt.row_num = cte.rn - 1
)
INSERT INTO database.table (id, bu, full_action)
SELECT id, bu, act
FROM cte
WHERE rn = 1;
DROP TABLE vt;
);
答案 0 :(得分:1)
DDL必须是Teradata宏中的 only 语句。
作为解决方法,您可以切换到一次定义的全局临时表,然后只需将其插入/选择即可,而不用创建CREATE VOLATILE TABLE。
但是在您的情况下,不需要临时表以及效率低下的递归处理即可获得“组连接”:
SELECT id, max(bu) -- maybe min(bu)?
XmlAgg(Concat(To_Char(comment_date, 'yyyy-mm-dd HH24:MI:SS'), ' ', action)
ORDER BY comment_date) (VARCHAR(5000)) AS full_action
FROM database.table1
GROUP BY 1
将给您类似的结果。
答案 1 :(得分:0)
要继续我的评论,您应该能够在同一条语句中定义多个CTE。使RECURSIVE CTE
起作用可能很棘手,但这听起来似乎是可行的。也许是这样的:
CREATE MACRO database.macro_insertion_tablename AS (
WITH vt (id, bu, full_action, row_num, cnt) AS
(
SELECT
id, bu,
CONCAT(TO_CHAR(comment_date, 'yyyy-mm-dd HH24:MI:SS'), ' ', action) AS full_action,
ROW_NUMBER() OVER (PARTITION BY id ORDER BY date DESC) AS row_num,
COUNT(*) OVER (PARTITION BY id) as cnt
FROM database.table1
),
RECURSIVE cte (id, bu, act, rn) AS
(
SELECT
id, bu
,CAST(full_action AS VARCHAR(5000)) AS full_action
,row_num
FROM vt
WHERE row_num = cnt
UNION ALL
SELECT
vt.id, vt.bu
,cte.act || ' / ' || vt.full_action
,vt.row_num
FROM vt
JOIN cte On vt.id = cte.id AND vt.row_num = cte.rn - 1
)
INSERT INTO database.table (id, bu, full_action)
SELECT id, bu, act
FROM cte
WHERE rn = 1;
);
我没有一个Teradata
系统可以测试,因此不是100%可以按原样工作,但是请尝试一下。您可能需要将RECURSIVE
更改为WITH RECURSIVE
,还需要将CTE
查询的顺序更改(即,将RECURSIVE
放在第一位)。看一下这两个链接:
Teradata Forum - Multiple With Clause
teradata Forum - Common Table Expressions