oracle查询应该在单列中填充从单行到三个不同行的三个不同列值以及一行生成的一列并且结果不应在列中包含空值
表:电信
id ---提供者---消费者---接收者
1 ---- vodaphone ---- t-mobile ----- AT& T
预计出来是
id ----- name ---- type
1 ---- vodaphone ----提供者
1 ---- t-mobile ----消费者
1 ---- AT& T --------接收器
答案 0 :(得分:0)
使用union all
的简单方法:
select id, provider as name, 'provider' from telecom union all
select id, consumer, 'consumer' from telecom union all
select id, receiver, 'receiver' from telecom ;
这将扫描telecom
三次。一种更有效的方法可能是:
select t.id,
(case which when 'provider' then provider
when 'consumer' then consumer
when 'receiver' then receiver
end) as name,
which
from telecom t cross join
(select 'provider' as which from dual union all
select 'consumer' as which from dual union all
select 'receiver' as which from dual
) x
答案 1 :(得分:0)
Oracle安装程序:
SET DEFINE OFF;
CREATE TABLE Telecom ( id, provider, consumer, receiver ) AS
SELECT 1, 'vodaphone', 't-mobile', 'AT&T' FROM DUAL;
<强>查询强>:
SELECT id,
name,
"type"
FROM telecom
UNPIVOT( name FOR "type" IN ( provider, consumer, receiver ) );
<强>输出强>:
ID NAME type
---------- --------- --------
1 vodaphone PROVIDER
1 t-mobile CONSUMER
1 AT&T RECEIVER
<强>更新强>:
SET DEFINE OFF;
CREATE TABLE Telecom ( id, col_provider, col_consumer, col_receiver ) AS
SELECT 1, 'vodaphone', 't-mobile', 'AT&T' FROM DUAL UNION ALL
SELECT 1, 't-mobile', NULL, 'EE' FROM DUAL;
<强>查询强>:
SELECT id,
name,
"type"
FROM telecom
UNPIVOT( name FOR "type" IN ( col_provider AS 'provider',
col_consumer AS 'consumer',
col_receiver AS 'receiver' ) );
<强>输出强>:
ID NAME type
---------- --------- --------
1 vodaphone provider
1 t-mobile consumer
1 AT&T receiver
1 t-mobile provider
1 EE receiver