Fetching column values based on SYSDATE
题
I have a table wchih has 2 columns. The definition is
CREATE TABLE LOGGING_T
(
TSTAMP DATE,
LINE VARCHAR2(300)
)
TABLESPACE OPERATIONS
MONITORING
/
The colulmn TSTAMP has values like 30-NOV-11
, 29-NOV-11
... and so on. Now i am doing this query
select * from LOGGING_T where TSTAMP >= (SYSDATE - 1)
The current system date is 01-DEC-11
. Ideally, the above statement should return records which has TSTAMP = 30-NOV-11
since i am doing SYSDATE-1
which would be 30-NOV-11
. But it isn't fetching those records. Why?
However, if i do this query
select * from LOGGING_T where TSTAMP >= (SYSDATE - 2)
Then it fetches records who TSTAMP
is 30-NOV-11
. Am i doing something wrong in this simple date operation?
解决方案
A DATE
contains time of day as well as the date.
If SYSDATE
was 2011-12-01 1:18:00 PM
then SYSDATE-1
would be 2011-11-30 1:18:00 PM
.
Are the rows you are expecting to find from November 30th before or after the time element?
If you don't care about the time, and only want to filter based on the date, you can use TRUNC()
:
select *
from LOGGING_T
where TRUNC(TSTAMP) >= TRUNC(SYSDATE - 1);
You'll may or may not want to make sure both sides of your comparison operator are TRUNC()
ed because TRUNC()
will just force the time element of the date to be midnight.
select to_char(trunc(sysdate), 'YYYY-MM-DD HH:MI:SS PM')
from dual;
NOW
----------------------
2011-12-01 12:00:00 AM
其他提示
The value SYSDATE has the time component as well. Most probably the date in your database also has the time component.
Change your query to :
select * from LOGGING_T where TSTAMP >= TRUNC(SYSDATE - 1)
to see all records which were logged from 00:00 yesterday.
To see the actual timecomponents, use to char.
SQL> select sysdate from dual;
SYSDATE
---------
01-DEC-11
1* select to_char(sysdate,'DD-Mon-YYYY HH24:MI:SS') date1 from dual
SQL> /
DATE1
--------------------
01-Dec-2011 16:29:01