问题
I'm trying to subtract date from Oracle so it even effect the day as well. For example, if the timestamp is 01/June/2015 00 hours and if I subtract 2 hours, I want to be able to go to to 31/May/2014 22 hours.
I tried
to_char(sysdate-(2/11), 'MM-DD-YYYY HH24')
but it only subtracts the hour; it does not touch the day itself.
回答1:
Others have commented on the (incorrect) use of 2/11
to specify the desired interval.
I personally however prefer writing things like that using ANSI interval
literals which makes reading the query much easier:
sysdate - interval '2' hour
It also has the advantage of being portable, many DBMS support this. Plus I don't have to fire up a calculator to find out how many hours the expression means - I'm pretty bad with mental arithmetics ;)
回答2:
Try this:
SELECT to_char(sysdate - (2 / 24), 'MM-DD-YYYY HH24') FROM DUAL
To test it using a new date instance:
SELECT to_char(TO_DATE('11/06/2015 00:00','dd/mm/yyyy HH24:MI') - (2 / 24), 'MM-DD-YYYY HH24:MI') FROM DUAL
Output is: 06-10-2015 22:00, which is the previous day.
回答3:
sysdate-(2/11)
To subtract hours from a DATE, you need to convert the hours in days. A day consists of 24 hours
, so to convert 2 hours
into days, you need to divide it by 24
.
Now, to subtract 2 hours form the date, do:
DATE_value - 2/24
For example,
SQL> SELECT TO_CHAR(
2 TO_DATE('01/Jun/2015 00:00:00', 'DD/Mon/YYYY HH24:MI:SS') - 2/24,
3 'DD/Mon/YYYY HH24:MI:SS') dt
4 FROM DUAL;
DT
--------------------
31/May/2015 22:00:00
SQL>
回答4:
date - n
will subtract n days form given date. In order to subtract hrs you need to convert it into day buy dividing it with 24. In your case it should be to_char(sysdate - (2 + 2/24), 'MM-DD-YYYY HH24')
. This will subract 2 days and 2 hrs from sysdate.
回答5:
you should divide hours by 24 not 11
like this:select to_char(sysdate - 2/24, 'dd-mon-yyyy HH24') from dual
来源:https://stackoverflow.com/questions/30772434/how-to-subtract-hours-from-a-date-in-oracle-so-it-affects-the-day-also