CREATE TABLE b( ID VARCHAR2(50 BYTE),
PARENT_ID VARCHAR2(50 BYTE),
NAME NVARCHAR2(200)
);
https://community.oracle.com/thread/3513540?
以上链接我解释了一切
答案 0 :(得分:0)
你不喜欢answer posted there的任何理由?说明问题答案的SQL Fiddle不是您所描述的所需结果吗?
修改强>:
使用SQL Fiddle Frank Kulash技术的suggested。这是我自2002年以来编写的第一个基于Oracle的查询(在9iAS上)。
SELECT REGEXP_SUBSTR( a.PIDPath, '[^,]+', 1, 1 ) Header1,
REGEXP_SUBSTR( a.IDPath, '[^,]+', 1, 1 ) Header2,
REGEXP_SUBSTR( a.NamePath, '[^,]+', 1, 1 ) Header3,
REGEXP_SUBSTR( a.PIDPath, '[^,]+', 1, 2 ) Header4,
REGEXP_SUBSTR( a.IDPath, '[^,]+', 1, 2 ) Header5,
REGEXP_SUBSTR( a.NamePath, '[^,]+', 1, 2 ) Header6,
REGEXP_SUBSTR( a.PIDPath, '[^,]+', 1, 3 ) Header7,
REGEXP_SUBSTR( a.IDPath, '[^,]+', 1, 3 ) Header8,
REGEXP_SUBSTR( a.NamePath, '[^,]+', 1, 3 ) Header9,
REGEXP_SUBSTR( a.PIDPath, '[^,]+', 1, 4 ) Header10,
REGEXP_SUBSTR( a.IDPath, '[^,]+', 1, 4 ) Header11,
REGEXP_SUBSTR( a.NamePath, '[^,]+', 1, 4 ) Header12,
REGEXP_SUBSTR( a.PIDPath, '[^,]+', 1, 5 ) Header13,
REGEXP_SUBSTR( a.IDPath, '[^,]+', 1, 5 ) Header14,
REGEXP_SUBSTR( a.NamePath, '[^,]+', 1, 5 ) Header15
--,REGEXP_SUBSTR( a.PIDPath, '[^,]+', 1, n )
--,REGEXP_SUBSTR( a.IDPath, '[^,]+', 1, n )
--,REGEXP_SUBSTR( a.NamePath, '[^,]+', 1, n )
FROM ( SELECT LEVEL RootLvl,
b.ID RootID,
SYS_CONNECT_BY_PATH( b.PARENT_ID, ',' )
|| ',' PIDPath,
SYS_CONNECT_BY_PATH( b.ID, ',' )
|| ',' IDPath,
SYS_CONNECT_BY_PATH( b.NAME, ',' )
|| ',' NamePath
FROM t b
START WITH b.PARENT_ID = '1'
CONNECT BY NOCYCLE PRIOR b.ID = b.PARENT_ID ) a
ORDER BY a.RootLvl, a.RootID;
Frank Kulash指出:
结果集中的列数必须硬编码到查询中。您可以编写今天生成30列的内容(即,层次结构中足够10个级别),但如果您稍后更改数据以便有11个或更多级别,那么您的查询将开始失去结果。
我可能会稍后再尝试PIVOT
。甲骨文很疯狂。
修改强>:
但足够可管理。静态PIVOT
有效just fine。我无法让CROSS APPLY
像我认为应该使用VALUES
(MSSQL样式)一样工作,所以我已经放弃并将其替换为可通过的UNION ALL
。有一些动态SQL工作的潜力,所以它实际上可以做你需要的而不需要对列进行硬编码。
;
WITH c ( RID, ID, PARENT_ID, NAME ) AS (
SELECT ROW_NUMBER() OVER (
ORDER BY PARENT_ID ) RID,
ID, PARENT_ID, NAME
FROM t
UNION ALL
SELECT b.RID, a.ID, a.PARENT_ID, a.NAME
FROM t a,
c b
WHERE a.ID = b.PARENT_ID
)
SELECT p."'ID_1'" Header1,
p."'PARENT_ID_1'" Header2,
p."'NAME_1'" Header3,
p."'ID_2'" Header4,
p."'PARENT_ID_2'" Header5,
p."'NAME_2'" Header6,
p."'ID_3'" Header7,
p."'PARENT_ID_3'" Header8,
p."'NAME_3'" Header9,
p."'ID_4'" Header10,
p."'PARENT_ID_4'" Header11,
p."'NAME_4'" Header12,
p."'ID_5'" Header13,
p."'PARENT_ID_5'" Header14,
p."'NAME_5'" Header15
FROM ( SELECT RID,
'ID_' || ROW_NUMBER() OVER (
PARTITION BY RID
ORDER BY ID ) KeyName,
ID KeyValue
FROM c
UNION ALL
SELECT RID,
'PARENT_ID_' || ROW_NUMBER() OVER (
PARTITION BY RID
ORDER BY ID ) KeyName,
PARENT_ID KeyValue
FROM c
UNION ALL
SELECT RID,
'NAME_' || ROW_NUMBER() OVER (
PARTITION BY RID
ORDER BY ID ) KeyName,
CAST( NAME AS VARCHAR2( 200 ) ) KeyValue
FROM c ) s
PIVOT ( MAX( KeyValue ) FOR KeyName IN (
'ID_1', 'PARENT_ID_1', 'NAME_1',
'ID_2', 'PARENT_ID_2', 'NAME_2',
'ID_3', 'PARENT_ID_3', 'NAME_3',
'ID_4', 'PARENT_ID_4', 'NAME_4',
'ID_5', 'PARENT_ID_5', 'NAME_5' ) ) p
ORDER BY p.RID;