0

two tables x and 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

what i want -

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

what i dont want to do -

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';

Is there another way ? I don't want to scan the same table 'y' thrice..

4

2 回答 2

2

As you are using 11g version of Oracle RDBMS, you can use pivot clause(if there are finite number of key values, because you'll have to manually specify them in the IN clause) to produce the desired result:

/* 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)
          )  
      )

Result:

      X_ID X_A   X_B   X_C   ABC DEF GHI
---------- ----- ----- ----- --- --- ---
         1 aval1 bval1 cval1 y1  y2  y3  
         2 aval2 bval2 cval2 y4      y5 
于 2013-10-21T17:23:09.650 回答
0

try this:

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;
于 2013-10-22T08:20:54.490 回答