SQL Server: Get data for only the past year

后端 未结 12 877
不思量自难忘°
不思量自难忘° 2020-12-12 17:09

I am writing a query in which I have to get the data for only the last year. What is the best way to do this?

SELECT ... FROM ... WHERE date > \'8/27/2007         


        
12条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 17:23

    GETDATE() returns current date and time.

    If last year starts in midnight of current day last year (like in original example) you should use something like:

    DECLARE @start datetime
    SET @start = dbo.getdatewithouttime(DATEADD(year, -1, GETDATE())) -- cut time (hours, minutes, ect.) --  getdatewithouttime() function doesn't exist in MS SQL -- you have to write one
    SELECT column1, column2, ..., columnN FROM table WHERE date >= @start
    

提交回复
热议问题