SELECT COALESCE (
(to_timestamp( '2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS')
- ('2014-09-22 09:00:00' ,'yyyy/mm/dd HH24:MI:SS'))
- (to_timestamp( '2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS')
- to_timestamp('2014-09-22 09:00:00.' ,'yyyy/mm/dd HH24:MI:SS'))
, '00:00')
FROM DUAL;
这是在postgres中工作,但它在oracle中不起作用。
答案 0 :(得分:9)
看起来你正试图用TIMESTAMP做数学(+, - )。 TIMESTAMP并不喜欢这样。你应该把TIMESTAMP CAST到DATE:
而不是 bla - blu(其中bla和blu是TIMESTAMP)do
CAST (bla as DATE) - CAST (blu as DATE)
and you will get a NUMBER (multiply it by 3600 * 24 and you will turn it into seconds)
BUT 你将失去毫秒信息
点击此链接timestamp difference
答案 1 :(得分:2)
将'00:00'
更改为INTERVAL '0' DAY
:
SELECT COALESCE (
(to_timestamp('2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS') - to_timestamp('2014-09-22 09:00:00','yyyy/mm/dd HH24:MI:SS')) -
(to_timestamp('2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS') - to_timestamp('2014-09-22 09:00:00','yyyy/mm/dd HH24:MI:SS')),
INTERVAL '0' DAY)
FROM DUAL;
更多信息:Interval Literals
答案 2 :(得分:1)
COALESCE
不是必需的。
NVL
就足够了。基本上,如果没有时差,那就是
将返回0. DATE
有时间部分,TIMESTAMP
数据类型是扩展名
DATE数据类型。除了DATE的datetime元素
数据类型,TIMESTAMP数据类型将一秒的分数保存到a
精度在0到9位小数之间,默认为6.所以,
在您的情况下,TO_DATE
更有意义。SQL> SELECT NVL( 2 (to_date( '2014-09-22 16:00:00','YYYY-MM-DD HH24:MI:SS') - to_date('2014-09-22 09:00:00','YYYY-MM-DD HH24:MI:SS')) 3 - (to_date('2014-09-22 16:00:00','YYYY-MM-DD HH24:MI:SS') - to_date('2014-09-22 09:00:00','YYYY-MM-DD HH24:MI:SS')) 4 ,0) DIFF 5 FROM DUAL 6 / DIFF ---------- 0 SQL>
对于其他值,要获得时间间隔的显着差异:
SQL> SELECT NVL(
2 (to_date( '2014-09-22 16:00:00','YYYY-MM-DD HH24:MI:SS') - to_date('2014-09-22 23:00:00','YYYY-MM-DD HH24:MI:SS'))
3 - (to_date('2014-09-22 16:00:00','YYYY-MM-DD HH24:MI:SS') - to_date('2014-09-22 09:00:00','YYYY-MM-DD HH24:MI:SS'))
4 ,0) DIFF
5 FROM DUAL
6 /
DIFF
----------
-.58333333
更新
由于日期的差异会返回一个数字,因此NVL
与TO_DATE
一起使用时不会返回interval
而是返回number
。在上面的例子中,它是0。
要获得区别,to_timestamp
是有意义的。所以,NVL和TO_TIMESTAMP会很好:
SQL> SELECT NVL (
2 (to_timestamp('2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS') - to_timestamp('2014-09-22 09:00:00','yyyy/mm/dd HH24:MI:SS')) -
3 (to_timestamp('2014-09-22 16:00:00','yyyy/mm/dd HH24:MI:SS') - to_timestamp('2014-09-22 09:00:00','yyyy/mm/dd HH24:MI:SS')),
4 INTERVAL '0' DAY) diff
5 FROM DUAL
6 /
DIFF
---------------------------------------------------------------------------
+000000000 00:00:00.000000000