Oracle Pivot query gives columns with quotes around the column names. What?

后端 未结 1 1707
天命终不由人
天命终不由人 2020-12-15 19:41

I\'m trying to use PIVOT in Oracle and I\'m getting a weird result. It\'s probably just an option I need to set but what I know about Oracle/SQL I could fit into this commen

相关标签:
1条回答
  • 2020-12-15 20:15

    you can provide aliases to the new columns in the pivot statement's IN clause. (NB: This is different from the standard where clause IN() which does not allow aliases.)

    with testdata as
    (
        select 'Fred' First_Name, 10 Items from dual
        union
        select 'John' First_Name, 5  Items from dual
        union 
        select 'Jane' First_Name, 12 Items from dual
        union
        select 'Fred' First_Name, 15 Items from dual
    )
    select * from testdata
    pivot (
          sum(Items) 
          for First_Name
          in ('Fred' as fred,'John' as john,'Jane' as jane)
          )
    

    and also for your aggregate clause which is necessary if you have multiple clauses..

    with testdata as
    (
        select 'Fred' First_Name, 10 Items from dual
        union
        select 'John' First_Name, 5  Items from dual
        union 
        select 'Jane' First_Name, 12 Items from dual
        union
        select 'Fred' First_Name, 15 Items from dual
    )
    select * from testdata
    pivot (
        sum(Items) itmsum,
        count(Items) itmcnt
        for First_Name
        in ('Fred' as fred,'John' as john,'Jane' as jane)
       )
    

    returns

    FRED_ITMSUM FRED_ITMCNT JOHN_ITMSUM JOHN_ITMCNT JANE_ITMSUM JANE_ITMCNT
    ----------- ----------- ----------- ----------- ----------- -----------
             25           2           5           1          12           1
    

    Of course you can then go full circle and use standard oracle aliasing and rename them to whatever you like including putting quotes back in again..

    with testdata as
    (
        select 'Fred' First_Name, 10 Items from dual
        union
        select 'John' First_Name, 5  Items from dual
        union 
        select 'Jane' First_Name, 12 Items from dual
        union
        select 'Fred' First_Name, 15 Items from dual
    )
    select FRED_ITMSUM "Fred's Sum", FRED_ITMCNT "Fred's Count"
         , JOHN_ITMSUM "John's Sum", JOHN_ITMCNT "John's Count"
         , JANE_ITMSUM "Janes's Sum", JANE_ITMCNT "Janes's Count"
    from testdata
    pivot (
        sum(Items) itmsum,
        count(Items) itmcnt
        for First_Name
        in ('Fred' as fred,'John' as john,'Jane' as jane)
       )
    

    gives

    Fred's Sum Fred's Count John's Sum John's Count Janes's Sum Janes's Count
    ---------- ------------ ---------- ------------ ----------- -------------
            25            2          5            1          12             1
    
    0 讨论(0)
提交回复
热议问题