find records from previous x days?

前端 未结 4 558
走了就别回头了
走了就别回头了 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
    
    0 讨论(0)
  • 2021-01-03 23:41

    Something like this?

      CREATE PROC GetSomeHistory
    
       @NumDaysPrevious   int
    
       AS
       BEGIN
           SELECT * FROM MyTable
           WHERE RequestDate BETWEEN DATEADD(dd, -1 * @NumDaysPrevious, getdate())
                                 AND getdate();
       END
    
       ......
    
       EXEC GetSomeHistory 55;
    
    0 讨论(0)
  • 2021-01-03 23:45

    Are you looking for last 30 days or last month? To find start and end of each month ("generic" as your comment says), use:

    select  dateadd(month,datediff(month,0,getdate()),0), 
        dateadd(mm,datediff(mm,-1,getdate()),-1)
    
    0 讨论(0)
  • 2021-01-03 23:46
    SELECT *
    FROM Table
    WHERE GETDATE() >= DATEADD(DAY, -30, GETDATE())
    

    Substitute the first GETDATE() with the appropriate column name.

    SELECT *
    FROM Table
    WHERE Table.ColumnName >= DATEADD(DAY, -30, GETDATE())
    
    0 讨论(0)
提交回复
热议问题