SQL Server: Get data for only the past year

后端 未结 12 833
不思量自难忘°
不思量自难忘° 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:18
    declare @iMonth int
    declare @sYear varchar(4)
    declare @sMonth varchar(2)
    set @iMonth = 0
    while @iMonth > -12
    begin
        set @sYear = year(DATEADD(month,@iMonth,GETDATE()))
        set @sMonth = right('0'+cast(month(DATEADD(month,@iMonth,GETDATE())) as varchar(2)),2)
        select @sYear + @sMonth
        set @iMonth = @iMonth - 1
    end
    
    0 讨论(0)
  • 2020-12-12 17:20

    Well, I think something is missing here. User wants to get data from the last year and not from the last 365 days. There is a huge diference. In my opinion, data from the last year is every data from 2007 (if I am in 2008 now). So the right answer would be:

    SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1
    

    Then if you want to restrict this query, you can add some other filter, but always searching in the last year.

    SELECT ... FROM ... WHERE YEAR(DATE) = YEAR(GETDATE()) - 1 AND DATE > '05/05/2007'
    
    0 讨论(0)
  • 2020-12-12 17:23

    Look up dateadd in BOL

    dateadd(yy,-1,getdate())
    
    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-12 17:25

    The following adds -1 years to the current date:

    SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())
    
    0 讨论(0)
  • 2020-12-12 17:29

    I, like @D.E. White, came here for similar but different reasons than the original question. The original question asks for the last 365 days. @samjudson's answer provides that. @D.E. White's answer returns results for the prior calendar year.

    My query is a bit different in that it works for the prior year up to and including the current date:

    SELECT .... FROM .... WHERE year(date) > year(DATEADD(year, -2, GETDATE()))

    For example, on Feb 17, 2017 this query returns results from 1/1/2016 to 2/17/2017

    0 讨论(0)
提交回复
热议问题