oracle查询将不同的列填充到一列中
Posted
技术标签:
【中文标题】oracle查询将不同的列填充到一列中【英文标题】:oracle query to populate different columns into one column 【发布时间】:2016-06-24 19:27:56 【问题描述】:什么应该是oracle查询将三个不同的列值从单行填充到单列中的三个不同行以及一列即时生成,结果不应在列中包含空值
表:电信id --- 提供者 --- 消费者 --- 接收者 1 ----vodaphone ---- t-mobile ----- AT&T
预计是id ----- 名称 ---- 类型 1 ---- vodaphone---- 供应商 1 ---- t-mobile ---- 消费者 1 ---- AT&T -------- 接收者
【问题讨论】:
【参考方案1】:一个简单的方法使用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
【讨论】:
【参考方案2】: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
【讨论】:
会忽略为空列创建行吗?如果我们的列名对于类型(例如 COL_Provider、COL_Consumer、COL_RECEIVER)不同,但又想按照上面给出的类型输出呢以上是关于oracle查询将不同的列填充到一列中的主要内容,如果未能解决你的问题,请参考以下文章
使用 Oracle 分析函数从使用 max 的列中获取数据而不是另一列