Amir Elsaeed
Amir Elsaeed

Reputation: 81

select one row from nested table type

my question is there away to select only one record from that column type as default value.

enter image description here

create type t_tel as table of number;

create table users_tel(
user_id number,
user_name varchar2(100),
tel t_tel
) nested table tel store as tel_table;

insert into users_tel(user_id, user_name, tel) values (1, 'Amir', t_tel(987,654,321));

select * from users_tel;

Upvotes: 0

Views: 2019

Answers (2)

Ftaveras
Ftaveras

Reputation: 719

You can use group by to do it:

select u.user_id, u.user_name, min(t.column_value) def_tel from users_tel u left join table(u.tel) t on 1=1 group by u.user_id, u.user_name;

Note that i am using left join with the table Type to show records where tel is null.

Upvotes: 1

MT0
MT0

Reputation: 168741

Use a table collection expression to treat the collection in the nested table as if it was a table and join on that. Then you can filter to get one row per user_id:

SQL Fiddle

Oracle 11g R2 Schema Setup:

create type t_tel as table of number;

create table users_tel(
  user_id number,
  user_name varchar2(100),
  tel t_tel
) nested table tel store as tel_table;

insert into users_tel(user_id, user_name, tel)
  SELECT 1, 'Amir',  t_tel(987,654,321) FROM DUAL UNION ALL
  SELECT 2, 'Dave',  t_tel(123,456)     FROM DUAL UNION ALL
  SELECT 3, 'Kevin', t_tel()            FROM DUAL;

Query 1:

SELECT user_id,
       user_name,
       tel_no
FROM   (
  SELECT u.*,
         t.column_value AS tel_no,
         ROW_NUMBER() OVER ( PARTITION BY u.user_id ORDER BY ROWNUM ) AS rn
  FROM   users_tel u
         LEFT OUTER JOIN
         TABLE( u.tel ) t
         ON ( 1 = 1 )
)
WHERE  rn = 1

Results:

| USER_ID | USER_NAME | TEL_NO |
|---------|-----------|--------|
|       1 |      Amir |    987 |
|       2 |      Dave |    123 |
|       3 |     Kevin | (null) |

Upvotes: 1

Related Questions