问题
I need to get all records with a date between Sunday and Saturday last week, inclusive, for whatever date the query is run. For today, April 19th 2011, that would be from April 10th to April 16th.
When I entered the dates manually and converted the filter to SQL, I got the following syntax:
RESOLVED_DATE BETWEEN timestamp '2011-04-10 00:00:00' AND timestamp '2011-04-16 00:00:00'
I'm not even sure this is correct, because it seems to exclude dates on the 16th itself (shouldn't the time be 23:59:59?)
回答1:
It is possible to determine the dates you want using combinations of next_day and regular date arithmetic. Below code should be pretty close, but it's untested and probably fails on some corner case, but at least you get the general idea :)
where resolved_date >= next_day( trunc(sysdate) - interval '14' day, 'SUN')
and resolved_date < next_day( trunc(sysdate) - interval '7' day, 'SUN')
trunc(sysdate)
truncate the date to day; 2011-04-19 23:32:34 becomes 2011-04-19 00:00:00, i.e. removing the time component.
next_day(sysdate, 'SUN')
returns the next sunday. If sysdate happens to be a sunday, the next sunday is returned.
Important: The day names have to be in the same language as your session.
The interval
thing is just a standard way of adding/subtracting different units of time from a date.
Putting it all together, the logic for the 19th of April 2011 would be:
- Truncate sysdate => 2011-04-19 00:00:00
- subtract 14 days => 2011-04-05 00:00:00
- Find the next sunday => 2011-04-10 00:00:00
...and
- Truncate sysdate => 2011-04-19 00:00:00
- subtract 7 days => 2011-04-12 00:00:00
- Find the next sunday => 2011-04-17 00:00:00
..resulting in the following query:
where resolved_date >= timestamp '2011-04-10 00:00:00'
and resolved_date < timestamp '2011-04-17 00:00:00'
All resolved_dates that happened on or after the first second of the 10:th but before the first second of the 17:th would be included. Note that >=
and <
isn't equivalent to between
.
A note on performance: I would make sure that Oracle correctly estimates the date range to be 7 days, and that the correct join order/method is used. If you expect the query to run for a while, you can afford to calculate the dates in the application and supply them as date litterals instead of computing them on the fly like I did above.
回答2:
take a look at the to_date function: http://psoug.org/reference/builtin_functions.html
来源:https://stackoverflow.com/questions/5720288/oracle-bi-select-all-records-from-last-week