如何在Netezza中使用自联接查找父记录

时间:2013-09-30 07:56:01

标签: sql join self netezza

我有一个带有键的表(即数字),如org_key和par_org_key

Org_key | Par_Org_key
52      26
23      89
26      14
14      8

在上面的表格中,org_key 52的父级是26,org_key 26的父级是14,依此类推 上述系列的根父级是8(因为它未在org_key列中列出)。 我需要找到这样的根,并在单行上有完整的链接,例如:8 | 14 | 26 | 52。

此SQL适用于Oracle:

select 
      substr(sys_connect_by_path(org_nbr,'|'),2)  spa
     ,substr(sys_connect_by_path(org_key,'|'),2)  org_key_line
     ,connect_by_root(org_key)                    org_key_root
     ,level                                       lvl
     ,org.*
from org
start with par_org_key is null
connect by par_org_key = prior org_key 

我的问题是,如何使用Netezza SQL执行相同的查询?

1 个答案:

答案 0 :(得分:1)

Netezza不支持递归公用表表达式,否则这将是更优雅和可扩展的解决方案。我发现最好的解决方法是在同一个表中使用Left Outer Joins。

创建一个测试表。我们使用-1来表示根节点。

CREATE TABLE t1 AS
SELECT 52 AS Org_key, 26 AS Par_Org_key
UNION
SELECT 23 AS Org_key, 89 AS Par_Org_key
UNION
SELECT 26 AS Org_key, 14 AS Par_Org_key
UNION
SELECT 14 AS Org_key, 8 AS Par_Org_key
UNION
SELECT 8 AS Org_key, -1 AS Par_Org_key;

返回8 | 14 | 26 | 52

SELECT NVL(a.Org_key,'0') || '|' || NVL(b.Org_key,'0') || '|' || NVL(c.Org_key,'0') || '|' || NVL(d.Org_key,'0')
FROM t1 a
LEFT OUTER JOIN t1 b ON a.Org_key = b.Par_Org_key
LEFT OUTER JOIN t1 c ON b.Org_key = c.Par_Org_key
LEFT OUTER JOIN t1 d ON c.Org_key = d.Par_Org_key
LEFT OUTER JOIN t1 e ON d.Org_key = e.Par_Org_key
WHERE a.Par_Org_key = -1;

如果你想添加更多左外连接以支持未知数量的级别,这可以帮助处理产生的空值

SELECT NVL(CAST(a.Org_key AS VARCHAR(10)),'') || '|' || NVL(CAST(b.Org_key AS VARCHAR(10)),'') || '|' || NVL(CAST(c.Org_key AS VARCHAR(10)),'') || '|' || NVL(CAST(d.Org_key AS VARCHAR(10)),'')