Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select first day of preceding month in (DB2) SQL

I need to check whether a given date is in the preceding month for a monthly query. I can get

CURRENT DATE - 1 MONTH

to compare the selected date with, but I can't assume the current date will be the first day of each month exactly. Is there a built in way to get the first day of the month without extracting the year and month and gluing it back together?

like image 515
nearly_lunchtime Avatar asked Jun 30 '09 11:06

nearly_lunchtime


People also ask

How do I get the first day of a month in SQL?

To find the first day, the date time is first converted to date only using TO_DATE function. Then, the date is changed to the first day of the month by using the DATE_FROM_PARTS function. This works by inputting 01' in the 'day' part of the function.

How do I find the difference between two dates in DB2?

*Subtract the two date values, divide by (60 seconds * 60 minutes * 24 hours * 365.25 days / 12 months). COMPUTE month1 = (date2 - date1) / (60 * 60 * 24 * 365.24 / 12)  . EXE  . *You may also use the DATEDIFF function.

How do I get the day of the week in DB2?

The DAYOFWEEK function returns an integer, in the range of 1 to 7, that represents the day of the week, where 1 is Sunday and 7 is Saturday. The DAYOFWEEK function is similar to the DAYOFWEEK_ISO function. The schema is SYSIBM.


2 Answers

First Day of the Current Month:

CURRENT_DATE - (DAY(CURRENT_DATE)-1) DAYS 

First of the Current Year is

CURRENT_DATE - (DAY(CURRENT_DATE)-1) DAYS - (MONTH(CURRENT_DATE)-1) MONTHS 

Last Day of the Last Month:

CURRENT_DATE - DAY(CURRENT_DATE) DAYS 

First Day of the Last Month:

CURRENT_DATE - (DAY(CURRENT_DATE)-1) DAYS - 1 MONTH 
like image 75
3 revs, 3 users 77%Chris Wolcott Avatar answered Oct 23 '22 18:10

3 revs, 3 users 77%Chris Wolcott


First day of this year:

date('0001-01-01') + year(current date) years - 1 year

First day of this month:

date('0001-01-01') + year(current date) years - 1 year + month(current date) months - 1 month

First day of last month:

date('0001-01-01') + year(current date) years - 1 year + month(current date) months - 2 months

If you don't need to maintain SQL compatibility with Db2 LUW v10.5 and older, you can also use these convenient Db2 LUW v11.1 scalar functions: THIS_WEEK() THIS_MONTH() THIS_QUARTER() and THIS_YEAR().

First day of this month:

THIS_MONTH(CURRENT DATE)

First day of last month:

THIS_MONTH(CURRENT DATE) - 1 MONTH

Last day of last month:

THIS_MONTH(CURRENT DATE) - 1 DAY
like image 28
Fred Sobotka Avatar answered Oct 23 '22 17:10

Fred Sobotka