Oracle 透视运算符

cab*_*oad 0 sql oracle

我是 oracle 枢轴的新手。这可能吗?

我有两列TypeValue

type     value
---------------
a        a1
b        b1
c        c1
etc
Run Code Online (Sandbox Code Playgroud)

我能在一行中得到这样的东西吗?

a   b    c 
a1  b1   c1
Run Code Online (Sandbox Code Playgroud)

在尝试这样的查询时,我得到了这样的输出

  select A,B from tbl
  pivot (max(value) for type in ('a' as A,'b' as B))

  ------------------------------------
    A    B
   null  b1
   a1    null
Run Code Online (Sandbox Code Playgroud)

谢谢

Nic*_*nov 5

您得到这样的输出仅仅是因为您select针对一个表(您的tbl表)发出语句,该表可能包含一个列(例如主键列),该列唯一标识一行,并且pivot运算符考虑了该列的值。这是一个简单的例子:

/*assume it's your table tbl */
with tbl(unique_col, col1, col2) as(
  select 1, 'a',  'a1' from dual union all
  select 2, 'b',  'b1' from dual union all
  select 3, 'c',  'c1' from dual
)
Run Code Online (Sandbox Code Playgroud)

针对此类表的查询将为您提供您在问题中提供的输出(不需要的输出):

select A,B 
  from tbl
pivot(
  max(col2) for col1 in ('a' as A,'b' as B)
)
Run Code Online (Sandbox Code Playgroud)

结果:

A    B
--   --
a1   null   
null b1
Run Code Online (Sandbox Code Playgroud)

为了产生所需的输出,您需要排除具有唯一值的行的列:

select A
     , B 
  from (select col1 
             , col2  /*selecting only those columns we are interested in*/
           from tbl ) 
  pivot(
    max(col2) for col1 in ('a' as A,'b' as B)
  )
Run Code Online (Sandbox Code Playgroud)

结果:

A  B
-- --
a1 b1 
Run Code Online (Sandbox Code Playgroud)