在这种情况下,我们如何在SQL中使用数据透视表?

时间:2019-07-12 17:21:20

标签: sql oracle pivot

表1

CODE      ID
A         1d
B         2f
C         1d
B         3r
C         2f
A         3r
D         8r

其中CODE和ID是非唯一列。

我想将其转换为

预期的查询结果:

A     B     C
1d   null  1d
null 2f    2f
3r   3r    null

在A,B和C分别是“ CODE”列中的记录,而我想将它们转换为列,  以及我们在代码中没有相邻ID的任何地方,我都希望它为null。

我尝试了

SELECT *
from TABLE 1
pivot (coalesce (id, 'null')  for CODE in ('A', 'B', 'C'))

完全错误

如果有人可以提供帮助,那将是一个很大的帮助。

很抱歉格式不正确,这是我的第一个问题。

2 个答案:

答案 0 :(得分:2)

此查询将显示您想要的结果:

select
  max(case when t.code = 'A' then t.id end) as a,
  max(case when t.code = 'B' then t.id end) as b,
  max(case when t.code = 'C' then t.id end) as c
from (select distinct id from table1 where code in ('A', 'B', 'C')) d
join table1 t on t.id = d.id
group by d.id
order by d.id

结果:

A       B       C      
------  ------  ------
1d      <null>  1d     
<null>  2f      2f     
3r      3r      <null>  

记录下来,这是我用来测试的数据脚本:

create table table1 (code varchar2(9), id varchar2(5));

insert into table1 (code, id) values ('A', '1d');
insert into table1 (code, id) values ('B', '2f');
insert into table1 (code, id) values ('C', '1d');
insert into table1 (code, id) values ('B', '3r');
insert into table1 (code, id) values ('C', '2f');
insert into table1 (code, id) values ('A', '3r');
insert into table1 (code, id) values ('D', '8r');

答案 1 :(得分:1)

with data (CODE , ID) as (
select 'A','1d' from dual union all 
select 'B','2f' from dual union all 
select 'C','1d' from dual union all 
select 'B','3r' from dual union all 
select 'C','2f' from dual union all 
select 'A','3r' from dual union all 
select 'D','8r' from dual
)
select A,B,C from (
  select code, id, substr(id,1,1) rn 
  from data
  where code in ('A', 'B', 'C')
)
pivot (max(id) for code in('A' as A, 'B' as B, 'C' as C))
order by rn;

A  B  C 
-- -- --
1d    1d
   2f 2f
3r 3r