This is very short and elegant. I tried to build multiple if statement and temp variable to store the last date and manipulate the next_date to get the last sunday (or any other date), but you solve it using one line of code
select last_day(sysdate) - mod(to_char(last_day(sysdate),'d') + offset,7) from dual;
For example, to get the last Wednesday of the month:
select last_day(sysdate) - mod(to_char(last_day(sysdate),'d')+3,7) from dual;
The mod function is needed to deal with the two possibilities that the last day of the month can be either earlier or later in the week than the day you are trying to calculate.
Karluk, you're happy man, because you work in default environment. In fact the result of aplying 'd' format mask depends on NLS_TERRITORY. In many countries the week starts from Monday. So a bit more complex but also more universal formula:
last_day(sysdate) - mod(7 + to_char(last_day(sysdate),'d')-<the day number you need in YOUR week>,7)
The less clear thing (7 + ) guarantees nonnegative result of mod() function.
If Wednesday is really the 4th day of the week the result is.
In fact the main idea was to switch from IMHo less obvious
to_char(last_day(sysdate),'d') + offset
to a bit clearer
to_char(last_day(sysdate),'d') - daynumber.
That's right, Carp. Your solution is very close to the solution we came up with in the thread from last November. It also works without added complexity for other days of the week. I think the only added wrinkle we came up with in November is a solution that will probably work in non-English speaking countries. We replaced the literal "Sunday" with a calculation based on a fixed date that we know falls on a Sunday. It's a nice feature for portability, but the basic strategy remains the same as your solution.
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.