0

Please consider this table:

Table1

NUMBER        NAME       
----------------------
01              A              
01              B        
02              A        
01              C        
02              C
03              C
04              C

I want to convert it to

Table2

NAME    NUM01   NUM02   NUM03   NUM04   NUM05
--------------------------------------------------
A       01      02      NULL    NULL    NULL
B       01      NULL    NULL    NULL    NULL
C       01      02      03      04      NULL

In Table2, the number of columns is fixed (NUM01->05). If NAME value has more than 5 NUMBER values, it just select top 5. If it has less than 5, then fill NULL in remain columns.

I have many different values in NAME column, so I can't think of an appropriate way to convert Table1 right.

Please help me.

0

1 Answer 1

1

Your 'number' values appear to be strings, and you can't have a column called number unless you use a quoted identifier, so I've substituted value to create your sample data:

create table table1(value varchar2(7), name varchar2(4));
insert into table1 (value, name)
select '01', 'A' from dual
union all select '01', 'B' from dual
union all select '02', 'A' from dual
union all select '01', 'C' from dual
union all select '02', 'C' from dual
union all select '03', 'C' from dual
union all select '04', 'C' from dual
/

You can use an analytic function to assign a row number or ranking to each value:

select name, value,
  row_number() over (partition by name order by value) as rn
from table1;

NAME VALUE           RN
---- ------- ----------
A    01               1
A    02               2
B    01               1
C    01               1
C    02               2
C    03               3
C    04               4

And then you can pivot that query (as long as you're on 11g or higher) to get the result you want:

select *
from (
  select name, value,
    row_number() over (partition by name order by value) as rn
  from table1
)
pivot (max(value) as value for (rn) in (1, 2, 3, 4, 5));

NAME 1_VALUE 2_VALUE 3_VALUE 4_VALUE 5_VALUE
---- ------- ------- ------- ------- -------
A    01      02                             
B    01                                     
C    01      02      03      04             

Anything ranked higher than 5 is ignored by the pivot operation.

Sign up to request clarification or add additional context in comments.

1 Comment

Excellent answer! Exactly what I need, thank you very much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.