我有一个像这样的源表:
id | code | description | parent_code | level
1 111 testone null 1
2 222 testtwo null 1
3 333 testthree 111 2
4 444 testfour 222 2
我必须将其上传到一个新表,结果如下:
id | codelevel1 | descriptionlevel1 | codeleve2 | descriptionlevel2
1 111 testone 333 testthree
2 222 testtwo 444 testfour
请注意,我总共有 6 个级别,因此在目标表中,我将 ...CodeLevel6 DescriptionLevel6 作为最后两列
我研究了WITH AS递归查询的使用,但目前我一直困惑于如何为唯一的现有ID填充codelevel1...codelevel6字段。
最佳答案
您需要一个分层查询来获取具有相同根元素的所有行,然后使用 PIVOT 转换数据:
SELECT *
FROM
(
SELECT CONNECT_BY_ROOT id AS root_id, code, description, lvl
FROM t
CONNECT BY parent_code = PRIOR code
START WITH parent_code IS NULL
)
PIVOT
(
MIN(code) AS code, MIN(description) AS description
FOR lvl IN ( 1, 2, 3, 4, 5, 6 )
)
使用 lvl IN ( 1, 2 )
会返回:
ROOT_ID 1_CODE 1_DESCRIPTION 2_CODE 2_DESCRIPTION
---------- ---------- ------------- ---------- -------------
1 111 testone 333 testthree
2 222 testtwo 444 testfour
关于sql - 将数据从行合并到列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47650250/