Oracle 行转列问题,求助大神

下面是原表和目标表,原表中一个ID多条数据,最多不超过5条
2025-02-27 14:03:33
推荐回答(1个)
回答1:

创建表插入数据:

create table test
(id int,
field int);


insert into test values (1,101);
insert into test values (1,102);
insert into test values (1,103);
insert into test values (2,36);
insert into test values (2,37);
insert into test values (2,38);
insert into test values (2,39);
commit;

执行:

select t.id,
       max(decode(rn, 1, field, null)) field1,
       max(decode(rn, 2, field, null)) field2,
       max(decode(rn, 3, field, null)) field3,
       max(decode(rn, 4, field, null)) field4,
       max(decode(rn, 5, field, null)) field5
  from (select test.*, row_number() over(partition by id order by field) rn
          from test) t
 group by t.id;

结果: