find records from previous x days?

前端 未结 4 560
走了就别回头了
走了就别回头了 2021-01-03 23:18

How can I come up with a stored procedure that selects results for past 30 days?

where MONTH(RequestDate) > 6 and DAY(RequestDate) >= 10 
and MONTH(Req         


        
4条回答
  •  悲哀的现实
    2021-01-03 23:34

    SELECT *
    FROM Table
    WHERE myDate >= DATEADD(MONTH, -1, GETDATE())
    

    doing it by month is different than doing it in 30-day blocks. Test this out as follows...

    declare @mydate smalldatetime
    set @mydate = '07/6/01'
    
    select @mydate
    select DATEADD(month, 2, @mydate), DATEDIFF(day, DATEADD(month, 2, @mydate), @mydate)
    select DATEADD(month, 1, @mydate), DATEDIFF(day, DATEADD(month, 1, @mydate), @mydate)
    select DATEADD(month, -1, @mydate), DATEDIFF(day, DATEADD(month, -1, @mydate), @mydate)
    select DATEADD(month, -2, @mydate), DATEDIFF(day, DATEADD(month, -2, @mydate), @mydate)
    select DATEADD(month, -3, @mydate), DATEDIFF(day, DATEADD(month, -3, @mydate), @mydate)
    

    Here are the results:

    2001-07-06 00:00:00
    2001-09-06 00:00:00   |   -62
    2001-08-06 00:00:00   |   -31
    2001-06-06 00:00:00   |   30
    2001-06-06 00:00:00   |   30
    2001-05-06 00:00:00   |   61
    2001-04-06 00:00:00   |   91
    

提交回复
热议问题