我可以使用任何oracle聚合函数代替此查询?

时间:2013-10-21 16:52:01

标签: sql oracle query-optimization

两张表x和y。

table x (id, a, b, c)
1, aval1, bval1, cval1
2, aval2, bval2, cval2

table y (xid, key, otherval)
1, ABC, y1
1, DEF, y2
1, GHI, y3
2, ABC, y4
2, GHI, y5

我想要的 -

x.id, x.a, x.b, x.c, ABC, DEF, GHI
1, aval1, bval1, cval1, y1, y2, y3
2, aval2, bval2, cval2, y4, -, y5

我不想做的事情 -

select
    x.id,
    a,
    b,
    c,
    ABC.otherval,
    DEF.otherval,
    GHI.otherval
from
    x,
    y ABC,
    y DEF,
    y GHI
where
    x.id = ABC.xid
    and x.id = DEF.xid
    and x.id = GHI.xid
    and ABC.key = 'ABC'
    and DEF.key = 'DEF'
    and GHI.key = 'GHI';

还有其他方法吗?我不想扫描同一张桌子'y'三次..

2 个答案:

答案 0 :(得分:2)

当您使用11g版本的Oracle RDBMS时,您可以使用pivot子句(如果有key个值有限,因为您必须在{{1}中手动指定它们}}子句产生所需的结果:

IN

结果:

/* sample of data */
with  x (id1, a1, b, c1) as(
  select 1, 'aval1', 'bval1', 'cval1' from dual union all
  select 2, 'aval2', 'bval2', 'cval2' from dual
),
y (xid1, key1, otherval) as(
  select 1, 'ABC', 'y1' from dual union all
  select 1, 'DEF', 'y2' from dual union all
  select 1, 'GHI', 'y3' from dual union all
  select 2, 'ABC', 'y4' from dual union all
  select 2, 'GHI', 'y5' from dual
)
/* the query */
select  v1_id1      as x_id 
      , v1_xa       as x_a
      , v1_ab       as x_b
      , v1_ac       as x_c
      , v1_otherval as ABC  
      , v2_otherval as DEF
      , v3_otherval as GHI
  from ( select *
           from x
           join y
             on (x.id1 = y.xid1)
          pivot (
                  max(x.id1) as id1
                , max(x.a1)  as xa
                , max(x.b)   as ab
                , max(x.c1)  as ac
                , max(y.otherval) as otherval for key1 in ( 'ABC' as v1
                                                          , 'DEF' as v2
                                                          , 'GHI' as v3)
          )  
      )

答案 1 :(得分:0)

试试这个:

select 
x.*,
(select y.otherval from y where x.id = y.xid and y.key = 'ABC') as ABC ,
(select y.otherval from y where x.id = y.xid and y.key = 'DEF') as DEF ,
(select y.otherval from y where x.id = y.xid and y.key = 'GHI') as GHI 
from x;