我正在尝试为一个新表准备数据,这个表是来自现有表的相同数据,但是是非规范化的。我有一个简单的场景,但我的头脑对返回结果的最有效方法感到空白。
它基于以下简化的场景:
Table X | Table y
id | id Identifier Value
123 | 123 1 A
| 123 2 B除了表X中的其他字段外,我还需要返回我的查询:
123 A B我考虑过:
解决方案一
select
id,
(select Value...),
(select Value...)...解决方案二:
select id,
y1.Value,
y2.Value
from x, y y1, y y2...解决方案三:使用PL/SQL并遍历游标
解决方案四:将y提取到两个表identifyer1和identifier2 (可能使用触发器)并将这些表连接到查询中
这些解决方案中的每一个都有一个很大的缺点,我相信有一个词可以提醒我解决这个问题的概念。
发布于 2013-02-28 20:46:02
除非我漏掉了什么东西,否则你是想把数据转到中心点。有几种方法可以做到这一点。
可以使用聚合函数和CASE表达式:
select x.id,
max(case when y.identifier = 1 then y.value end) Value1,
max(case when y.identifier = 2 then y.value end) Value2
from tablex x
left join tabley y
on x.id = y.id
group by x.id请参阅与Demo
根据您的Oracle版本,您可以使用PIVOT函数:
select id,
Value1,
Value2
from
(
select x.id, y.identifier, y.value
from tablex x
left join tabley y
on x.id = y.id
)
pivot
(
max(value)
for identifier in ('1' as Value1, '2' as Value2)
) piv请参阅与Demo
您可以多次加入:
select x.id,
y1.value Value1,
y2.value Value2
from tablex x
left join tabley y1
on x.id = y1.id
and y1.identifier = 1
left join tabley y2
on x.id = y2.id
and y2.identifier = 2见与Demo。
如果您正在寻找动态解决方案,则可以使用sys_refcursor创建一个过程:
CREATE OR REPLACE procedure dynamic_pivot(p_cursor in out sys_refcursor)
as
sql_query varchar2(8000) := 'select x.id ';
begin
for x in (select distinct identifier from tabley order by 1)
loop
sql_query := sql_query ||
' , max(case when y.identifier = '||x.identifier||' then y.value else null end) as Value'||x.identifier;
dbms_output.put_line(sql_query);
end loop;
sql_query := sql_query || ' from tablex x
left join tabley y
on x.id = y.id
group by x.id';
dbms_output.put_line(sql_query);
open p_cursor for sql_query;
end;
/这些解决方案为每个值提供了单独列的结果。如果要将数据放在单个列中,则可以使用LISTAGG()
select x.id,
listagg(y.value, ' ') within group (order by y.id) as Value
from tablex x
left join tabley y
on x.id = y.id
group by x.id请参阅与Demo
https://stackoverflow.com/questions/15145078
复制相似问题