SQL Server SQL get First day of month 3 months before current Month

p5cysglq  于 2023-06-21  发布在  其他
关注(0)|答案(2)|浏览(131)

I am trying to select the first day of the month 3 months before the current date.

so for example if the current date was: '2015-11-08' my result would want to be: '2015-08-01'

I would prefer if this was in yyyy-mm-dd format.

I tried this to start with but had no luck:

SELECT DATEADD(dd, -DAY('2015-09-01') + 1, @today)

I have tried numerous things but cannot seem to crack it, any advice or help would be appreciated. Thank you in advance

wh6knrhe

wh6knrhe1#

The logic is simple:

  • Subtract the day of the month minus 1 days from the date
  • Subtract three months

In SQL Server:

select dateadd(month, -3, dateadd(day, 1 - day(dte), dte))

For the current date:

select cast(dateadd(month, -3, dateadd(day, 1 - day(getdate()), getdate())) as date)

And as a string:

select convert(varchar(10),
               dateadd(month, -3, dateadd(day, 1 - day(getdate()), getdate())),
               120)
pbpqsu0x

pbpqsu0x2#

select dateadd(month, -3, dateadd(day, -2, '2014-09-03'))

相关问题