2011-12-09 62 views
2

我想調換使用查詢類似於下面的行列...甲骨文UNPIVOT和SYSDATE給人怪異的結果

WITH 
query AS 
(
    SELECT SYSDATE AS SomeDate, 
       'One' AS One, 
       'Two' AS Two, 
       'Three' AS Three, 
       'Four' AS Four, 
       'Five' AS Five 
     FROM dual 
), 
up_query AS 
(
    SELECT * 
    FROM query 
    UNPIVOT 
    ( 
    NUM FOR DUMMY 
    IN 
    ( 
     One AS 'One', 
     Two AS 'Two', 
     Three AS 'Three', 
     Four AS 'Four', 
     Five AS 'Five' 
    ) 
    ) 
) 
SELECT SYSDATE, b.* 
    FROM up_query b; 

我期待SomeDate以反映結果行SYSDATE ... 但這是我得到的結果:

SYSDATE SOMEDATE  DUMMY NUM 
09-DEC-11 09-DEC-07  One One 
09-DEC-11 09-DEC-07  Two Two 
09-DEC-11 09-DEC-07  Three Three 
09-DEC-11 09-DEC-07  Four Four 
09-DEC-11 09-DEC-07  Five Five 

爲什麼SOMEDATE比SYSDATE早4年?

回答

2

正如馬克在他的回答中提到,這是Oracle 11.2.0.1和11.2.0.2版本ATLEAST的錯誤。

但是根據this文章,如果您遇到以上提到的Oracle版本,即將日期轉換爲varchar格式,然後將其轉換回日期數據類型,則有一種解決方法。

所以查詢現在應該是:

WITH 
query AS 
(
    SELECT  TO_CHAR(SYSDATE, 'RRRRMMDD') AS SomeDate, 
       'One' AS One, 
       'Two' AS Two, 
       'Three' AS Three, 
       'Four' AS Four, 
       'Five' AS Five 
     FROM dual 
), 
up_query AS 
(
    SELECT * 
    FROM query 
    UNPIVOT 
    ( 
    NUM FOR DUMMY 
    IN 
    ( 
     One AS 'One', 
     Two AS 'Two', 
     Three AS 'Three', 
     Four AS 'Four', 
     Five AS 'Five' 
    ) 
    ) 
) 
SELECT SYSDATE, TO_DATE(SomeDate, 'RRRRMMDD') AS ActualSomeDate, b.*, 
    FROM up_query b; 
+2

你也可以通過用'cast(SYSDATE as date)'替換'SYSDATE'來修復它。顯然SYSDATE是一種特殊的數據類型,並不總是一個DATE。看到這個詢問湯姆線程:http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:910228941137#47403557344816此外,你可以看到這個奇怪的類型轉換與此查詢:'選擇dump(sysdate),dump(cast(sysdate as date))from dual;' –

3

這似乎是11.2.0.2中的一個錯誤。我可以在Linux x86-64,11.2.0.2上重現您的結果。

但是,在11.2.0.3,在Linux的x86-64,我得到:

$ sqlplus/as sysdba 

SQL*Plus: Release 11.2.0.3.0 Production on Sat Dec 10 01:20:32 2011 

Copyright (c) 1982, 2011, Oracle. All rights reserved. 


Connected to: 
Oracle Database 11g Enterprise Edition Release 11.2.0.3.0 - 64bit Production 
With the Partitioning, Real Application Clusters, Automatic Storage Management, OLAP, 
Data Mining and Real Application Testing options 

SQL> WITH 
    2 query AS 
    3 (
    4  SELECT SYSDATE AS SomeDate, 
    5    'One' AS One, 
    6    'Two' AS Two, 
    7    'Three' AS Three, 
    8    'Four' AS Four, 
    9    'Five' AS Five 
10   FROM dual 
11 ), 
12 up_query AS 
13 (
14  SELECT * 
15  FROM query 
16  UNPIVOT 
17  (
18  NUM FOR DUMMY 
19  IN 
20  (
21  One AS 'One', 
22  Two AS 'Two', 
23  Three AS 'Three', 
24  Four AS 'Four', 
25  Five AS 'Five' 
26  ) 
27  ) 
) 
28 29 SELECT SYSDATE, b.* 
30 FROM up_query b; 

SYSDATE SOMEDATE DUMMY NUM 
--------- --------- ----- ----- 
10-DEC-11 10-DEC-11 One One 
10-DEC-11 10-DEC-11 Two Two 
10-DEC-11 10-DEC-11 Three Three 
10-DEC-11 10-DEC-11 Four Four 
10-DEC-11 10-DEC-11 Five Five 
+0

你是對的。它至少是Oracle 11.2.0.1和11.2.0.2版本中的一個錯誤。但是有一個解決方案。檢查我的答案。 – Chandu