如何将列转换为行层次结构

问题描述 投票:0回答:1

我正在尝试将 4 列转换为行,但采用分层结构。

Col1        Col2        Col3              Col4
YP HEVEA    YP HEVEA    OTHER CREDITORS   L1220001 - OTHER CREDITORS
YP HEVEA    YP HEVEA    PREPAYMENTS       A1323004 - PREPAYMENTS OTHERS
YP HEVEA    YP HEVEA    PREPAYMENTS       A2349032 - PREPAYMENTS NEW

我的要求是将其转换为树层次结构中的单个列,如下所示。

LEVLE     COLUMN
1         YP HEVEA
2         YP HEVEA
3A        OTHER CREDITORS
4A        L1220001 - OTHER CREDITORS
3B        PREPAYMENTS
4B        A1323004 - PREPAYMENTS OTHERS
4B        A2349032 - PREPAYMENTS NEW

我添加了 LEVEL 列只是为了显示我想要的顺序,但这在输出中不是必需的。我正在尝试使用 UNPIVOT 但不知道如何实施。

这是测试数据

SELECT 
'YP HEVEA' Col1,   'YP HEVEA' Col2,   'OTHER CREDITORS' Col3,  'L1220001 - OTHER CREDITORS' Col4
FROM DUAL
UNION
SELECT 
'YP HEVEA' Col1,   'YP HEVEA' Col2,   'PREPAYMENTS' Col3,      'A1323004 - PREPAYMENTS OTHERS' Col4
FROM DUAL
UNION
SELECT 
'YP HEVEA' Col1,   'YP HEVEA' Col2,   'PREPAYMENTS' Col3,       'A2349032 - PREPAYMENTS NEW' Col4
FROM DUAL
sql oracle-sqldeveloper
1个回答
0
投票

使用

UNPIVOT

SELECT DISTINCT col, lvl
FROM   table_name
       UNPIVOT(
         col FOR lvl IN (
           col1 AS 1,
           col2 AS 2,
           col3 AS 3,
           col4 AS 4
         )
       )

对于样本数据:

CREATE TABLE table_name (col1, col2, col3, col4) AS
SELECT 'YP HEVEA', 'YP HEVEA', 'OTHER CREDITORS',  'L1220001 - OTHER CREDITORS' FROM DUAL UNION ALL
SELECT 'YP HEVEA', 'YP HEVEA', 'PREPAYMENTS', 'A1323004 - PREPAYMENTS OTHERS' FROM DUAL UNION ALL
SELECT 'YP HEVEA', 'YP HEVEA', 'PREPAYMENTS', 'A2349032 - PREPAYMENTS NEW' FROM DUAL;

输出:

科尔 LVL
YP橡胶树 1
YP橡胶树 2
其他债权人 3
L1220001 - 其他债权人 4
预付款 3
A1323004 - 预付款其他 4
A2349032 - 预付款新 4

小提琴

© www.soinside.com 2019 - 2024. All rights reserved.