我有以下查询:
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 的情况下起作用?
答案 0 :(得分:4)
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;