有没有PL/SQL函数来统计一个超类型的n个子类型的个数?

Is there a PL/SQL function to count the number of n subtypes of a super type?

PL/SQL中是否有一个函数可以计算table(超类型)的n个子类型的数量?

我试过以下方法:

select
    count(distinct value(t1))
from table t1;

select
    count(distinct treat(value(t1))
from table t1;

基本上,如果 table 有 6 个子类型,我想要一个可以输出 6 个的查询。

Oracle 设置:

CREATE TYPE parent_type AS OBJECT( id NUMBER ) NOT FINAL;
CREATE TYPE child1_type UNDER parent_type ( c1 NUMBER );
CREATE TYPE child2_type UNDER parent_type ( c2 NUMBER ) NOT FINAL;
CREATE TYPE child3_type UNDER child2_type ( c3 NUMBER );

CREATE TABLE test_data ( value parent_type );

INSERT INTO test_data ( value )
  SELECT parent_type( 1 ) FROM DUAL UNION ALL
  SELECT child1_type( 2, 1 ) FROM DUAL UNION ALL
  SELECT child1_type( 3, 1 ) FROM DUAL UNION ALL
  SELECT child1_type( 4, 1 ) FROM DUAL UNION ALL
  SELECT child2_type( 5, 2 ) FROM DUAL UNION ALL
  SELECT child2_type( 6, 2 ) FROM DUAL UNION ALL
  SELECT child3_type( 7, 3, 1 ) FROM DUAL UNION ALL
  SELECT child3_type( 8, 3, 1 ) FROM DUAL UNION ALL
  SELECT child3_type( 9, 3, 1 ) FROM DUAL;

查询 1:

如果您知道类型层次结构,那么您可以手动构建查询,如果您传递的对象不是该类型,则 TREAT( object AS type ) 将 return NULL 并且可以使用 CASE 语句并从层次结构树的叶子开始,处理从最深继承深度到父类型的类型:

SELECT COUNT( DISTINCT
         CASE
         WHEN TREAT( value AS child3_type ) IS NOT NULL
           THEN 'child3_type' -- deepest subtype
         WHEN TREAT( value AS child2_type ) IS NOT NULL
           THEN 'child2_type' -- supertype of child3_type, subtype of parent_type
         WHEN TREAT( value AS child1_type ) IS NOT NULL
           THEN 'child1_type' -- subtype of parent_type
         ELSE 'parent_type'
         END
       ) AS num_types
FROM   test_data

查询 2:

如果您有权访问 SYS.ANYDATA type then you can

SELECT COUNT(
         DISTINCT
         SYS.ANYDATA.getTypeName(
           SYS.ANYDATA.convertObject( value )
         )
       ) AS num_types
FROM   test_data

输出:

两者给出相同的输出:

| NUM_TYPES |
| --------: |
|         4 |

db<>fiddle here