Oracle pivot operator

前端 未结 2 1233
花落未央
花落未央 2020-12-04 01:12

I am new to oracle pivot. Is this possible?

I have two columns Type and Value

type     value
---------------
a        a1
b          


        
相关标签:
2条回答
  • 2020-12-04 01:39

    Something like this:

    SELECT a, b, c
      FROM tbl
     PIVOT
     (
       MAX(Value) FOR Type IN ('a' as a, 
                               'b' as b, 
                               'c' as c)
     )
    

    For more details you can refer to this documentation.

    0 讨论(0)
  • 2020-12-04 01:59

    You are getting the output like that simply because you are issuing select statement against a table (your tbl table) which presumably contains a column(primary key column for instance) which uniquely identifies a row and pivot operator takes into consideration values of that column. Here is a simple example:

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

    A query against such a table will give you that output(undesirable output) you provided in the question:

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

    Result:

    A    B
    --   --
    a1   null   
    null b1
    

    In order to produce desired output, you need to exclude the column with unique value for a row:

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

    Result:

    A  B
    -- --
    a1 b1 
    
    0 讨论(0)
提交回复
热议问题