I have a table with records from many dates. I would like to perform a query that only returns records that fall on the last day of the date's month. Something like:
SELECT * FROM mytable
WHERE DATEPART(d, mytable.rdate) = DATEPART(d,DATEADD(m,1,DATEADD(d, -1, mytable.rdate)))
Except this doesn't work as the rdate
in the right-hand side of the argument should be the last day of it's month for the dateadd
to return the correct comparison.
Basically is there an concise way to do this comparison? An equivalent for quarter-ends would also be very helpful, but no doubt more complex.
EDIT:
Essentially I want to check if a given date is the last in whatever month (or quarter) it falls into. If it is, return that record. This would involve a some function to return the last day of the month of any date. e.g. lastdayofmonth('2013-06-10') = 30
(so this record would not be returned.
EDIT2:
For the case of returning the records that fall on the last day of the quarter they are in it would need to be something like:
SELECT * FROM mytable
WHERE DATEPART('d', mytable.rdate) = lastdayofmonth(mytable.rdate)
AND DATEPART('m', mytable.rdate) = lastmonthofquarter(mytable.rdate);
The tricky bit is the lastdayofmonth()
and lastmonthofquarter()
functions