Hierarchical query in Teradata

huangapple go评论87阅读模式
英文:

Hierarchical query in Teradata

问题

我有如下层次数据。

|序列号 | 主要标志 |上一个序列号|
| 101 | 1 | 56 |
| 56 | 0 | NULL |
| 505 | 0 | NULL |
| 223 | 1 | 156 |
| 156 | 0 | 93 |
| 93 | 0 | 42 |
42 | 0 | NULL |

前两行在主要标志为1时与上一个序列号相关联,因此它们的层次总数为2。

第三行与任何内容都不相关,因为上一个序列号为NULL,所以总计为0。

第四行与下面的3条记录相关联,所以总数为4。

我需要一个查询来查找主要标志为1时行的总相关计数。在Teradata中如何实现这一点?

英文:

I have hierarchical data as follows.

  1. |Serial No | Primary Flag |Prev SerialNo|
  2. | 101 | 1 | 56 |
  3. | 56 | 0 | NULL |
  4. | 505 | 0 | NULL |
  5. | 223 | 1 | 156 |
  6. | 156 | 0 | 93 |
  7. | 93 | 0 | 42 |
  8. 42 | 0 | NULL |

First two rows are related by Previous serial number when primary flag, so total counts in their hierarchy is 2

Third row is not related to any thing since Previous serial number is NULL., so total count is 0.

Fourth row is related to below 3 records, so total count is 4.

I need a query to find the total related counts for rows when Primary flag is 1.How can I achieve this in Teradata?

答案1

得分: 2

以下是代码的中文翻译:

  1. 假设您不想为Serial_No 505返回一行记录,您可以使用递归查询和聚合:
  2. WITH RECURSIVE r AS (
  3. 选择 h.Serial_No AS Primary_SerialNoh.Serial_Noh.Prev_SerialNo1(整数)作为级别
  4. hierTbl h WHERE h.Primary_Flag=1
  5. UNION ALL
  6. 选择 r.Primary_SerialNoh.Serial_Noh.Prev_SerialNor.Level+1
  7. hierTbl h JOIN r ON r.Prev_SerialNo = h.Serial_No
  8. )
  9. 选择 Primary_SerialNoMAX(Level)作为Related
  10. r GROUP BY 1;

希望这对您有所帮助。

英文:

Assuming you don't want to return a row for Serial_No 505, you can use a recursive query and aggregation:

  1. WITH RECURSIVE r AS (
  2. SELECT h.Serial_No AS Primary_SerialNo, h.Serial_No, h.Prev_SerialNo, 1 (INTEGER) as Level
  3. FROM hierTbl h WHERE h.Primary_Flag=1
  4. UNION ALL
  5. SELECT r.Primary_SerialNo, h.Serial_No, h.Prev_SerialNo, r.Level+1
  6. FROM hierTbl h JOIN r ON r.Prev_SerialNo = h.Serial_No
  7. )
  8. Select Primary_SerialNo, MAX(Level) as Related
  9. FROM r GROUP BY 1;

huangapple
  • 本文由 发表于 2023年2月7日 04:48:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366428.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定