oracle 将列作为级别的表转换为层次结构

juud5qan  于 2023-06-29  发布在  Oracle
关注(0)|答案(1)|浏览(119)

如何将具有级别的Oracle表转换为Oracle层次结构表。
原始表结构:

需要的表结构:

edqdpe6u

edqdpe6u1#

您可以用途:

SELECT id,
       CASE LEVEL
       WHEN 1 THEN level_1
       WHEN 2 THEN level_2
       WHEN 3 THEN level_3
       WHEN 4 THEN level_4
       WHEN 5 THEN level_5
       END As value,
       PRIOR id As parent
FROM   table_name
START WITH level_2 IS NULL
CONNECT BY
       PRIOR level_1 = level_1
AND    (  (PRIOR level_2 IS NULL AND level_2 IS NOT NULL AND level_3 IS NULL)
       OR (PRIOR level_2 = level_2 AND PRIOR level_3 IS NULL AND level_3 IS NOT NULL AND level_4 IS NULL)
       OR (PRIOR level_2 = level_2 AND PRIOR level_3 = level_3 AND PRIOR level_4 IS NULL AND level_4 IS NOT NULL AND level_5 IS NULL)
       OR (PRIOR level_2 = level_2 AND PRIOR level_3 = level_3 AND PRIOR level_4 = level_4 AND PRIOR level_5 IS NULL AND level_5 IS NOT NULL)
       )

其中,对于样本数据:

CREATE TABLE table_name (id, level_1, level_2, level_3, level_4, level_5) AS
SELECT 1, 'Fasteners', NULL, NULL, NULL, NULL FROM DUAL UNION ALL
SELECT 2, 'Fasteners', 'Nails', NULL, NULL, NULL FROM DUAL UNION ALL
SELECT 3, 'Fasteners', 'Nails', 'Nuts washers', NULL, NULL FROM DUAL UNION ALL
SELECT 4, 'Fasteners', 'Nails', 'Nuts washers', 'Nuts', NULL FROM DUAL UNION ALL
SELECT 5, 'Fasteners', 'Nails', 'Nuts washers', 'Nuts', 'Hex nuts' FROM DUAL UNION ALL
SELECT 11, 'Power tools', NULL, NULL, NULL, NULL FROM DUAL UNION ALL
SELECT 12, 'Power tools', 'Power saws', NULL, NULL, NULL FROM DUAL UNION ALL
SELECT 13, 'Power tools', 'Power saws', 'Band saws', NULL, NULL FROM DUAL UNION ALL
SELECT 14, 'Power tools', 'Power saws', 'Circular saws', NULL, NULL FROM DUAL;

输出:
| 价值|父母| PARENT |
| - -----|- -----| ------------ |
| 紧固件|联系我们| null |
| 指甲|一个| 1 |
| 螺母垫圈|2| 2 |
| 坚果|三个| 3 |
| 六角螺母|4| 4 |
| 电动工具|联系我们| null |
| 动力锯|十一| 11 |
| 带锯|十二岁| 12 |
| 圆锯|十二岁| 12 |
fiddle

相关问题