Oracle Pivoting返回月/年的Null值

时间:2015-01-16 14:27:45

标签: oracle null pivot-table

我正在尝试根据日期(字段DT)按月/年轮换此表:

  CREATE TABLE "TEMP" 
   (    "NAME" VARCHAR2(20 BYTE), 
        "DT" DATE, 
        "SZ" NUMBER(10,0)
   )

Insert into TEMP (NAME,DT,SZ) values ('A',to_date('16/01/15','DD/MM/RR'),'1');
Insert into TEMP (NAME,DT,SZ) values ('B',to_date('16/01/15','DD/MM/RR'),'2');
Insert into TEMP (NAME,DT,SZ) values ('C',to_date('16/01/15','DD/MM/RR'),'3');
Insert into TEMP (NAME,DT,SZ) values ('D',to_date('16/01/15','DD/MM/RR'),'4');
Insert into TEMP (NAME,DT,SZ) values ('A',to_date('10/01/15','DD/MM/RR'),'5');
Insert into TEMP (NAME,DT,SZ) values ('B',to_date('10/01/15','DD/MM/RR'),'6');
Insert into TEMP (NAME,DT,SZ) values ('C',to_date('10/01/15','DD/MM/RR'),'7');

使用此查询:

SELECT * from
  (select name, sz, dt from temp) 
  pivot (sum(sz) for dt in (to_date('01/2015', 'MM/YYYY') as "dt"))

我收到了这个:

NAME                         dt
-------------------- ----------
D                               
A                               
B                                
C     

然而,我除了得到:

NAME                         dt
-------------------- ----------
D                             4 
A                             6  
B                             8   
C                            10 

我尝试了很多东西,但似乎没有一个像以下那样工作:

...
pivot (sum(sz) for dt in ('01/2015' as "dt")) --01843. 00000 -  "not a valid month"

你是否知道我做错了什么?

非常欢迎任何帮助。

1 个答案:

答案 0 :(得分:2)

您需要使用TO_CHAR而不是TO_DATE

WITH pivotdata AS 
( 
       SELECT name, 
              sz, 
              To_char(dt, 'MM/YYYY') dt1 
       FROM   temp ) 
SELECT * 
FROM   pivotdata pivot (SUM(sz) FOR dt1 IN ('01/2015') );

这将返回

NAME    '01/2015'
D   4
A   6
B   8
C   10