简体   繁体   中英

How can I use GETDATE() to get month and year from the past month?

How can I get it to one statement that can get me last month and this year?

I have a INSERT INTO and in a column report_date [datetime]

insert into table_a (report_date) values ( ??);

i want to show this past month and year, So for example today is 4/21/2014 so it would show 3/2014 in the column If today was MAY 1 2014 , it would show 4/2014? Is this possible or does it have to have a day?

您正在寻找DATEADD函数:

SELECT DATEPART(month, DATEADD(month, -1, GETDATE()), DATEPART(year, DATEADD(month, -1, GETDATE())

If you are trying to get 'last month' with 'this year' you could do:

SELECT CAST(
  CAST(YEAR(GETDATE()) AS VARCHAR) + '-' + 
  CAST(MONTH(GETDATE())-1 AS VARCHAR) + '-' + 
  CAST(DAY(GETDATE())  AS VARCHAR)
AS DATETIME)

But then in JAN 2015, it would return DEC 2015. If you just want last month, use the 'DATEADD' function.

SELECT DATEADD(MONTH, -1, GETDATE())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM