How to get the looop equivalent command in teradata

筅森魡賤 提交于 2019-12-11 20:00:34

问题


I am very new to Teradata. Here I dont see any looping command to execute the following-- Input Structure

 A  B  C
 -- -- --
 1  b  c
 1  d  d
 1  c  d
 1 fx  b

Output_Structure--

A  B  C
-- -- --
1 fx  b
1  b  c
1  c  d
1  d  d

here if we implement with the CASE structure it will work, like

CASE
IF (B ='fx' THEN SELECT C AS A1)
CASE
IF(B!= 'fx' THEN SELECT C WHERE B=A1)

but if the number of records are more then we need to implement through LOOP. So any suggestion on this.


回答1:


This looks like a hierarchy, you need some recursive query for that.

WITH RECURSIVE cte (i, a,b,c) AS
(
  SELECT 1 AS i,a,b,c 
  FROM tab
  WHERE b = 'fx' -- start with the first value

  UNION ALL

  SELECT cte.i + 1, tab.* 
  FROM tab, cte
  WHERE cte.c = tab.b -- traverse the hierarchy
  AND cte.a = tab.a
  AND cte.b <> cte.c -- stop if b=c
)
SELECT * FROM cte
ORDER BY i

This might result in a loop if there'a a row like d-b, but 1 AS i will error out if it exceeds 127, the max value of a byteint.

Protecting from infinite loop will be more complicated...

Edit:

To protect from infinite loop you need to create a path and check of the new value is already within the existing path:

WITH RECURSIVE cte (i, PATH, a,b,c) AS
(
  SELECT CAST(1 AS SMALLINT) AS i,
     '.' || CAST(TRIM(b) AS VARCHAR(10000)) || '.',
     a,b,c 
  FROM tab
  WHERE b = 'fx'

  UNION ALL

  SELECT cte.i + 1, 
     cte.PATH || TRIM(tab.b) || '.',
     tab.* 
  FROM tab, cte
  WHERE cte.c = tab.b
  AND cte.a = tab.a
  AND cte.PATH NOT LIKE '%.' || TRIM(tab.b) || '.%'
)
SELECT * FROM cte
ORDER BY 1;

The size of the path VarChar must be large enough to accommodate the largest possible recursion level.




回答2:


Are you looking for order by?

select t.*
from table t
order by c, b, a;

"looping" in databases is used with set-based operations, such as joins and group by.



来源:https://stackoverflow.com/questions/25888997/how-to-get-the-looop-equivalent-command-in-teradata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!