简体   繁体   中英

Return data with date from 2 months ago (using Oracle SQL)

I wonder if anyone has a solution to this problem. I'm trying to return results where the Worker's termination date is in the month from 2 months ago, so if the report is run in October, I want to see people with termination dates in August.

At present the best I can come up with is

Where Month(saw_4) = month(SYSDATE)-2

But this isn't going to work for SYSDATE of Jan and Feb. (Plus it doesn't seem to want to run anyway on Oracle OTBI, so I'll do in BI I think)

SELECT "Worker"."Person Number" AS saw_0, 
"Worker"."Employee Last Name" AS saw_1, 
"Worker"."Employee First Name" AS saw_2, 
"Worker"."Primary National Identifier Number" AS saw_3, 
"Worker"."Termination Date" AS saw_4 
FROM "Workforce Management - Work Relationship Real Time" 
Where Month(saw_4) = month(SYSDATE)-2

Any help gratefully received.

That might be something like this:

where termination_date between trunc(add_months(sysdate, -2), 'mm')
                           and last_day(add_months(sysdate, -2))

Why, if there's simpler

where to_char(termination_date, 'yyyymm') = to_char(add_months(sysdate, -2), 'yyyymm')

Because this will cause possible index on termination_date to be unusable (unless you have a function-based index, and people usually do not).

I would be inclined to write this as:

where termination_date >= trunc(add_months(sysdate, -2), 'mm') and
      termination_date < trunc(add_months(sysdate, -1), 'mm') 

Presumably, termination_date does not have a time component. But, alas, in Oracle the date data type always does have one. So this seems safer as a general solution.

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