使用 oracle sql 将行转换为列

converting rows to columns using oracle sql

我正在尝试使用以下示例将行转换为列:

LVL COL_VALUE TABLE_SRC
16 INT: ADDRESS_LINE_2:NULL INT
16 BASE: ADDRESS_LINE_2:X BASE
17 INT: ADDRESS_LINE_3:NULL INT
17 BASE: ADDRESS_LINE_3:X BASE

输出应该是:

INT BASE
INT: ADDRESS_LINE_2:NULL BASE: ADDRESS_LINE_2:X
INT: ADDRESS_LINE_3:NULL BASE: ADDRESS_LINE_3:X

相同LVL的COL_VALUE应该在1行

我尝试使用 PIVOT,但由于聚合函数returns它只有 1 行

SELECT *
    FROM
        (
        SELECT 
                 BATCH_ID
                ,CONTACT_ID
                ,COL_VALUE
                ,TABLE_SRC
        FROM
            MISMATCH
        )
PIVOT
    (
        max(COL_VALUE) FOR TABLE_SRC IN ('1BASE' BASE, '1INT' INT)
    )

您可以在内部子查询中包含 LVL

SELECT *
FROM   (
  SELECT  BATCH_ID
         ,CONTACT_ID
         ,COL_VALUE
         ,TABLE_SRC
         ,LVL
  FROM   MISMATCH
) PIVOT (
  max(COL_VALUE)
  FOR TABLE_SRC IN ('1BASE' BASE, '1INT' INT)
)

如果您不希望它出现在输出中,请将 SELECT * 更改为列列表。

其中,对于您的示例数据:

CREATE TABLE mismatch (batch_id, contact_id, LVL, COL_VALUE, TABLE_SRC) AS
SELECT 1, 1, 16, 'INT: ADDRESS_LINE_2:NULL', '1INT'  FROM DUAL UNION ALL
SELECT 1, 1, 16, 'BASE: ADDRESS_LINE_2:X',   '1BASE' FROM DUAL UNION ALL
SELECT 1, 1, 17, 'INT: ADDRESS_LINE_3:NULL', '1INT'  FROM DUAL UNION ALL
SELECT 1, 1, 17, 'BASE: ADDRESS_LINE_3:X',   '1BASE' FROM DUAL;

输出:

BATCH_ID CONTACT_ID LVL BASE INT
1 1 16 BASE: ADDRESS_LINE_2:X INT: ADDRESS_LINE_2:NULL
1 1 17 BASE: ADDRESS_LINE_3:X INT: ADDRESS_LINE_3:NULL

db<>fiddle here