Tuesday 3 January 2012

Teradata -Finding 1st and last day of month using SQL

Most of the time our queries need to have filtering conditions to fetch data only for a month.
In such cases its very imp to find the first and last day of the month.
Below its shown how to find 1st and last date of a given month.


1) 1st day:

select datecol - extract(day from datecol) + 1

This subtracts the number of days since the beginning of the month, taking you to "day 0", or the day before the first of the month; then adds 1.

2) Last day:

select add_months((datecol - extract(day from datecol)+1),1)-1

Same idea, but this computes the first day of the following month and then subtracts 1.

No comments:

Post a Comment