find records from previous x days?

2019-02-11 17:27发布

问题:

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(RequestDate) < 21 and DAY(RequestDate) < 7

回答1:

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())


回答2:

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)


回答3:

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;


回答4:

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