How to find the parent record using self join in N

2019-10-18 17:20发布

我有钥匙(即只能使用数字)作为org_key和par_org_key表

Org_key | Par_Org_key
52      26
23      89
26      14
14      8

另外,在上述tablem org_key 52的父是26,org_key 26的父是14上的根父用于上述串联的,以便为8(因为它没有在org_key列中列出)。 我需要找到这样的根,有完整的链接如:8 | 14 | 26 |在单排52。

这个SQL是工作在甲骨文:

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相同的查询?

Answer 1:

Netezza公司不支持递归公用表表达式,否则这将是一个更优雅的和可扩展的解决方案。 我已经找到了最好的解决办法是使用左外连接到同一个表。

创建一个测试表。 我们用-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)),'')


文章来源: How to find the parent record using self join in Netezza