Working with dates is fun. In this post we are going to show a method to easily find the first and last date of the
current month,
previous month, and
next month.
Knowledge
about this will come in handy if you i.e. want to do a year-over-year
sales analysis, or maybe you would like to take the current month’s
sales figures and compare them to what is budgeted for next month’s
sale.
Depending
on how your data is organized or partitioned, there are time you want
to use the last date of a month in i.e. a BETWEEN statement in SQL.
Here is a query that selects the first and
last date of a month, for last month,
current month, and
next month.
1 | SELECT TRUNC(SYSDATE) today |
3 | ,TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, -1), 'YYYYMM' ), 'YYYYMM' ) first_date_last_month |
4 | ,TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, 0), 'YYYYMM' ), 'YYYYMM' ) - 1 last_date_last_month |
7 | ,TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, 0), 'YYYYMM' ), 'YYYYMM' ) first_date_this_month |
8 | ,TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, + 1), 'YYYYMM' ), 'YYYYMM' ) - 1 last_date_this_month |
11 | ,TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, + 1), 'YYYYMM' ), 'YYYYMM' ) first_date_next_month |
12 | ,TO_DATE(TO_CHAR(ADD_MONTHS(SYSDATE, + 2), 'YYYYMM' ), 'YYYYMM' ) - 1 last_date_next_month |
No comments :
Post a Comment