简体   繁体   中英

SQL pull data for the past two years

How can I pull data from my table for just the past two years?

Current attempt which isn't recognizing "DATEADD":

select * 
from TABLE 
where EVENTDATE >= DATEADD(year, -1, GETDATE())

PL/SQL suggests Oracle. The correct logic is:

where eventdate >= sysdate - interval '2' year

Oracle can be finicky about interval arithmetic in general, add_months() is a good habit:

where eventdate >= add_months(sysdate, -24)

Of course, it depends what you mean by "2 year". If you mean since Jan 1st of the last calendar year:

where eventdate >= trunc(sysdate, 'YYYY') - interval '1' year

There is no problem when subtracting a year from January 1st.

Assuming Oracle and 2 years as 730 days you can do as simple as:

select *
  from table_name 
  where eventdate >= sysdate -730
;

When you add or subtract numbers from dates, oracle interpret the numbers as days.

Be aware that date is actually a date-time type and sysdate returns the current date-time. So if you are executing this query now at 10 pm it won't get the rows at 9 pm 2 years ago. Only the rows that are 10 pm or later.

You can remove (actually zero) the time of a date type doing trunc(sysdate) -730 .

Also, the trunc function has more options. See the documentation .

Following code is ugly but will do the job for you:)

select *
  from TABLE
 where EVENTDATE >= TO_DATE(to_char(SYSDATE, 'YYYY') - 1 || '-' || to_char(SYSDATE, 'MM-DD'),'YYYY-MM-DD')

You can use the ADD_MONTHS function to compare to a valid date, 2 years in the past:

select * 
from TABLE 
where EVENTDATE >= ADD_MONTHS(sysdate, -24)

Note: sysdate - interval '2' year will not yield a valid date on leap days (will raise exception ORA-01839), but ADD_MONTHS will give a valid date each time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM