首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Oracle SQL查询去Oracle

Oracle SQL查询去Oracle
EN

Stack Overflow用户
提问于 2013-02-28 20:30:52
回答 1查看 4.9K关注 0票数 1

我正在尝试为一个新表准备数据,这个表是来自现有表的相同数据,但是是非规范化的。我有一个简单的场景,但我的头脑对返回结果的最有效方法感到空白。

它基于以下简化的场景:

代码语言:javascript
复制
Table X   | Table y
id        | id    Identifier  Value
123       | 123   1           A
          | 123   2           B

除了表X中的其他字段外,我还需要返回我的查询:

代码语言:javascript
复制
123 A B

我考虑过:

解决方案一

代码语言:javascript
复制
select 
id,
(select Value...),
(select Value...)...

解决方案二:

代码语言:javascript
复制
select id,
y1.Value,
y2.Value
from x, y y1, y y2...

解决方案三:使用PL/SQL并遍历游标

解决方案四:将y提取到两个表identifyer1和identifier2 (可能使用触发器)并将这些表连接到查询中

这些解决方案中的每一个都有一个很大的缺点,我相信有一个词可以提醒我解决这个问题的概念。

EN

回答 1

Stack Overflow用户

发布于 2013-02-28 20:46:02

除非我漏掉了什么东西,否则你是想把数据转到中心点。有几种方法可以做到这一点。

可以使用聚合函数和CASE表达式:

代码语言:javascript
复制
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函数:

代码语言:javascript
复制
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

您可以多次加入:

代码语言:javascript
复制
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创建一个过程:

代码语言:javascript
复制
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()

代码语言:javascript
复制
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

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15145078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档