ORA-01790: 表达式必须与 UNPIVOT 查询中的相应表达式具有相同的数据类型

ORA-01790: expression must have same datatype as corresponding expression in UNPIVOT query

我有一个逆透视查询,从一个 table:

中提取时效果很好
WITH test
 (SELECT field1,field2,field3,field4
  FROM Table1
  WHERE id = 1234)
 SELECT * FROM test
 UNPIVOT 
 (Value FOR Field IN (field1 as 'Field 1', field2 as 'Field 2', field3 as 'Field 3', field4 as 'Field 4'))

将数据显示为:

Field 1    Value1
Field 2    Value2
Field 3    Value3
Field 4    Value4

现在我已将查询更改为拉取

WITH test
(SELECT t.field1,t.field2,t.field3,t.field4, x.qty1, x.qty2, (x.qty1 + x.qty2) qty3
FROM Table1 t
 ,(select id, field1, Function1(field1, field3) qty1, Function2(field1, field3) qty2 FROM Table1) x
WHERE t.id = x.id
AND id = 1234)
SELECT * FROM test
UNPIVOT 
(Value FOR Field IN (field1 as 'Field 1', 
field2 as 'Field 2', 
field3 as 'Field 3', 
field4 as 'Field 4',  <-- ORA-01790: expression must have same datatype as corresponding expression
qty1 as 'Quantity 1', 
qty2 as 'Quantity 2', 
qty3 as 'Total'))

不确定为什么会这样,我该如何解决

您的 field1field4 值是(或看起来是)字符串,而您的 qty1qty3 值是数字。正如错误消息所说,它们都需要是相同的数据类型。

您可能会感到困惑,因为该消息似乎与第一个查询 field4 中的原始列之一相关,而不是与新列之一相关。那是因为语句通常是向后解析的,所以解析器首先看到数字列,并抱怨第一个非数字列。

无论如何,您只需要在内部查询中将您的数字转换为字符串,例如:

WITH test
(SELECT t.field1,t.field2,t.field3,t.field4,
  to_char(x.qty1) as qty1, to_char(x.qty2) as qty2, to_char(x.qty1 + x.qty2) as qty3
...

或完整:

WITH test AS
(SELECT t.field1,t.field2,t.field3,t.field4,
  to_char(x.qty1) as qty1, to_char(x.qty2) as qty2, to_char(x.qty1 + x.qty2) as qty3
FROM Table1 t
 ,(select id, field1, Function1(field1, field3) qty1, Function2(field1, field3) qty2 FROM Table1) x
WHERE t.id = x.id
AND id = 1234)
SELECT * FROM test
UNPIVOT 
(Value FOR Field IN (field1 as 'Field 1', 
field2 as 'Field 2', 
field3 as 'Field 3', 
field4 as 'Field 4',
qty1 as 'Quantity 1', 
qty2 as 'Quantity 2', 
qty3 as 'Total'))

db<>fiddle demo 使用 dual 的虚拟值而不是你的真实值 table.

当然,您可以在这些 to_char() 调用中应用显式格式 - 我只是简单地演示了这个问题。


您可能会遇到其他错误 - 例如 AND id = 1234 会产生歧义 - 最好使用现代连接语法。我不确定你为什么要加入 - 你可以将内部查询简化为:

WITH test AS (
  SELECT field1, field2, field3, field4,
    to_char(qty1) as qty1, to_char(qty2) as qty2, to_char(qty1 + qty2) as qty3
  FROM (
    SELECT field1, field2, field3, field_4,
      Function1(field1, field3) as qty1, Function2(field1, field3) as qty2
    FROM Table1
    WHERE id = 1234
  )
)

db<>fiddle 添加了嵌套查询版本。