Oracle - 用来自另一个 table 的连接替换数据透视列的空值

Oracle - Replace null values for pivot columns with join from another table

我有一个数据透视表 table 输出,现在我想检查数据透视表列中的值,如果空值来自另一列 table.

Invoice_No Column value
111 A One
111 B Two
111 C Three
111 E Five
(SELECT Invoice_No, new_value, Column_Name  FROM table_name)
PIVOT(max(new_value) 
FOR Column_Name IN ('A','B','C','D','E'))

这返回了以下 table

Invoice_No 'A' 'B' 'C' 'D' 'E'
111 One Two Three null Five

现在,我想将 D 列中的空值替换为另一个 table 中匹配 Invoice_no 的值。

with temp as
(SELECT Invoice_No, new_value, Column_Name  FROM table_name)
PIVOT(max(new_value) 
FOR Column_Name IN ('A','B','C','D','E'))
select nvl(temp.D,bckup.D)
from
(select A,B,C,D,E from Backup_table) bckup
join
temp
on
temp.Invoice_No = bckup = Invoice_No

现在,我收到错误消息,提示 D 列不存在。

Pivot 会将您的列重命名为 'D' 而不仅仅是 D。因此,您需要在查询中进行简单更新,如 -

WITH temp AS(SELECT *
               FROM(SELECT Invoice_No, new_value, Column_Name
                      FROM table_name)
              PIVOT(max(new_value) FOR Column_Name IN ('A' AS A,'B' AS B,'C' AS C,'D' AS D,'E' AS E)
            )
SELECT NVL(temp.D,bckup.D)
  FROM(SELECT A,B,C,D,E
         FROM Backup_table) bckup
  JOIN temp ON temp.Invoice_No = bckup.Invoice_No