Oracle SQL:使用具有用户定义类型的 LAG 函数 returns "inconsistent datatypes"

Oracle SQL: using LAG function with user-defined-type returns "inconsistent datatypes"

我有一个类型 MyType 定义如下:

create or replace type MyType as varray(20000) of number(18);

和一个table MyTable定义如下:

create table MyTable (
   id       number(18) primary key
  ,widgets  MyType
)

我正在尝试 select 使用以下 SQL:

MyTable 中每一行及其逻辑上一行的小部件
select  t.id
       ,lag(t.widgets,1) over (order by t.id) as widgets_previous
from MyTable t
order by t.id;

我得到回复:

ORA-00932: inconsistent datatypes: expected - got MYSCHEMA.MYTYPE

如果我 运行 使用类型为 varchar 或 number 的列而不是 MyType 的完全相同的查询,它工作正常。

当前行和上一行的列类型必须相同,所以我只能假设它与用户定义的类型有关。

我是否需要做一些特殊的事情才能将 LAG 与用户定义的类型一起使用,或者 LAG 不支持用户定义的类型?如果是后者,是否有任何其他实用函数可以提供相同的功能,或者我是否需要进行传统的自连接才能实现相同的功能?

您可以将 lag 与 UDT 一起使用。问题是varray

这给你结果了吗?

select  t.id
       ,lag(
              (select listagg(column_value, ',') within group (order by column_value) 
                  from table(t.widgets))
            ,1) over (order by t.id) as widgets_previous
from MyTable t
order by t.id;

阅读以上所有内容后,我选择以下方法作为实现我所需的最有效方法:

select curr.id
      ,curr.widgets  as widgets
      ,prev.widgets  as previous_widgets
from (select  a.id                                      
             ,a.widgets
             ,lag(a.id,1) over (order by a.id)  as previous_id
      from mytable a
     ) curr
     left join mytable prev on (prev.id = curr.previous_id)
order by curr.id

即。一个滞后/自连接混合体,在它不抱怨识别连接条件的数字字段上使用滞后。我认为它相当整洁,我得到了我想要的 collections。感谢大家的宝贵意见。

您可以尝试类似的方法:

SQL> create or replace type TestType as varray(20000) of number(18);
Type created.
SQL> create table TestTable (
   id       number(18) primary key
  ,widgets  TestType
)
Table created.
SQL> delete from testtable
0 rows deleted.
SQL> insert into TestTable values (1, TestType(1,2,3,4))
1 row created.
SQL> insert into TestTable values (2, TestType(5,6,7))
1 row created.
SQL> insert into TestTable values (3, TestType())
1 row created.
SQL> insert into TestTable values (4,null)
1 row created.
SQL> commit
Commit complete.

SQL> -- show all data with widgets
SQL> select t.id, w.column_value as widget_ids
from testtable t, table(t.widgets) w

        ID WIDGET_IDS
---------- ----------
         1          1
         1          2
         1          3
         1          4
         2          5
         2          6
         2          7

7 rows selected.
SQL> -- show with lag function
SQL> select t.id, lag(w.column_value, 1) over (order by t.id) as widgets_previous
from testtable t, table(t.widgets) w

        ID WIDGETS_PREVIOUS
---------- ----------------
         1                 
         1                1
         1                2
         1                3
         2                4
         2                5
         2                6

7 rows selected.