修改查询以在不需要设置 NLS_DATE_FORMAT 的情况下工作

Modifying a query to work without requiring NLS_DATE_FORMAT to be set

我查询如下:

SELECT
    trunc(estimatedenddate,'hh') AS reg_date,
    COUNT(*)
FROM
    (
        SELECT
            attr_value,
            TO_DATE( (DATE '1970-01-01' + (1 / 24 / 60 / 60 / 1000) * attr_value),'yyyy-mm-dd HH24:mi:ss') AS estimatedenddate
        FROM
            attr
        WHERE
            attr_name = 'createTimestamp'
    )
WHERE
    estimatedenddate > TO_DATE('01/JUN/2018','dd/mon/yyyy')
GROUP BY
    trunc(estimatedenddate,'hh')
ORDER BY
    reg_date DESC;

当我设置 NLS_DATE_FORMAT 时它起作用了。参见 dbfiddle

但是如果我不设置 NLS_DATE_FORMAT,查询不会产生任何结果。参见 dbfiddle

如何修改此查询,使其在不设置 NLS_DATE_FORMAT 的情况下运行?

TO_DATE( date_string, format_model ) 将字符串作为第一个参数,但您传递的是 DATE 数据类型,Oracle 将尝试提供帮助并使用其默认格式模型隐式转换为预期的字符串数据类型;所以你的内部查询实际上是:

SELECT attr_value,
       TO_DATE(
         TO_CHAR(
           DATE '1970-01-01' + (1 / 24 / 60 / 60 / 1000) * attr_value,
           (SELECT value FROM NLS_SESSION_PARAMETERS WHERE parameter = 'NLS_DATE_FORMAT')
         ),
         'yyyy-mm-dd HH24:mi:ss'
       ) AS estimatedenddate
FROM   attr
WHERE  attr_name = 'createTimestamp'

相反,您可以删除 TO_DATE() 函数:

SELECT trunc(estimatedenddate,'hh') AS reg_date,
       COUNT(*)
FROM   (
  SELECT DATE '1970-01-01' + (1 / 24 / 60 / 60 / 1000) * attr_value AS estimatedenddate
  FROM   attr
  WHERE  attr_name = 'createTimestamp'
)
WHERE    estimatedenddate > DATE '2018-06-01'
GROUP BY trunc(estimatedenddate,'hh')
ORDER BY reg_date DESC;