如何在Oracle的一列中显示各行中的数据?

时间:2020-07-06 18:15:24

标签: sql oracle oracle11g

我有一个样本表,看起来像这样

create table test (
uname   varchar2(20),
seq     number,
sub_id  number,
sub_val varchar2(20)
);

insert into test values ('a1',1,1,'t1');
insert into test values ('a1',1,2,'t2');
insert into test values ('a1',1,3,'t3');

insert into test values ('a1',2,1,'t4');
insert into test values ('a1',2,2,'t5');
insert into test values ('a1',2,3,'t6');

insert into test values ('b1',1,1,'t7');
insert into test values ('b1',1,2,'t8');

insert into test values ('b1',2,1,'t9');
insert into test values ('b1',2,3,'t10');

select * from test;

我想在Oracle SQL中以以下格式显示该数据。 SQL查询可能吗? (基本上,uname + seq组合的所有sub_id都应出现在1列中。因此ColA将具有sub_id = 1的数据,而ColB将具有sub_id = 2的数据,依此类推。对于任何uname + seq组合,依此类推。)

enter image description here

2 个答案:

答案 0 :(得分:1)

您可以使用条件聚合:

select uname, seq,
       max(case when sub_id = 1 then sub_val end) as a,
       max(case when sub_id = 2 then sub_val end) as b,
       max(case when sub_id = 3 then sub_val end) as c
from test
group by uname, seq;

答案 1 :(得分:0)

您可以按以下方式使用PIVOT

SELECT * FROM
(SELECT UNAME, SEQ,SUB_ID,SUB_VAL FRO TEST)
PIVOT
(MAX(SUB_VAL) FOR SUB_ID IN (1 AS A,2 AS B, 3 AS C))
相关问题