选择嵌套表列符合条件

时间:2018-02-08 20:15:19

标签: sql oracle user-defined-types

v 的定义如下:create or replace type v is table of number \ temp 是一个包含v类型列的表。

我想选择v.count为3的行,但我会收到编译错误。是因为v.count是PL / SQL代码吗?

我尝试将代码放在匿名块中,但它仍无效。

使用游标是唯一的解决方案吗?

 SELECT *
 FROM emp
 WHERE V.COUNT = 3;

感谢。

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找cardinality()

  

CARDINALITY返回嵌套表中的元素数。返回类型为NUMBER。如果嵌套表为空,或者是空集合,则CARDINALITY将返回NULL

所以你可以这样做:

SELECT *
FROM emp
WHERE cardinality(V) = 3;

快速演示:

create or replace type v is table of number
/

create table emp (id number, v v)
nested table v store as v_tab;

insert into emp (id, v) values (1, v(1));
insert into emp (id, v) values (2, v(1,2));
insert into emp (id, v) values (3, v(1,2,3));
insert into emp (id, v) values (4, v(1,2,3,4));

column v format a30
set feedback 1

SELECT *
FROM emp
WHERE cardinality(V) = 3;

        ID V                             
---------- ------------------------------
         3 V(1, 2, 3)                    

1 row selected. 

答案 1 :(得分:1)

我喜欢亚历克斯的基数答案,这是另一种方法:

create or replace type num_type as table of number;

create table table_with_num_type
(
ids num_type,
val varchar2(100)
)
nested table ids store as ids_tab ;

insert into table_with_num_type(ids, val) values (num_type(1,2,3), 'TEST1');
insert into table_with_num_type(ids, val) values (num_type(4,5,6,7), 'TEST2');
commit;

select t.val, count(t2.column_value) as num_count
from table_with_num_type t, table(t.ids) t2
group by t.val
having count(t2.column_value) = 3;

结果:

VAL NUM_COUNT
TEST1   3