sql >> Base de Datos >  >> RDS >> Oracle

La consulta de Oracle Pivot proporciona columnas con comillas alrededor de los nombres de las columnas. ¿Qué?

puede proporcionar alias a las nuevas columnas en el pivot declaración IN cláusula. (NB:Esto es diferente del estándar donde la cláusula IN() que no permite alias.)

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

y también para su cláusula agregada que es necesaria si tiene varias cláusulas.

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

regresa

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

Por supuesto, puede completar el círculo y usar el alias estándar de Oracle y cambiarles el nombre a lo que quiera, incluso volver a poner comillas.

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

da

Fred's Sum Fred's Count John's Sum John's Count Janes's Sum Janes's Count
---------- ------------ ---------- ------------ ----------- -------------
        25            2          5            1          12             1