查找前x天的记录?

时间:2011-07-21 21:25:27

标签: sql sql-server tsql

如何创建一个选择过去30天结果的存储过程?

where MONTH(RequestDate) > 6 and DAY(RequestDate) >= 10 
and MONTH(RequestDate) < 21 and DAY(RequestDate) < 7

4 个答案:

答案 0 :(得分:30)

SELECT *
FROM Table
WHERE GETDATE() >= DATEADD(DAY, -30, GETDATE())

用适当的列名替换第一个GETDATE()。

SELECT *
FROM Table
WHERE Table.ColumnName >= DATEADD(DAY, -30, GETDATE())

答案 1 :(得分:4)

您是在寻找最近30天还是上个月?要查找每个月的开始和结束(如评论所示,“通用”),请使用:

select  dateadd(month,datediff(month,0,getdate()),0), 
    dateadd(mm,datediff(mm,-1,getdate()),-1)

答案 2 :(得分:2)

这样的东西?

  CREATE PROC GetSomeHistory

   @NumDaysPrevious   int

   AS
   BEGIN
       SELECT * FROM MyTable
       WHERE RequestDate BETWEEN DATEADD(dd, -1 * @NumDaysPrevious, getdate())
                             AND getdate();
   END

   ......

   EXEC GetSomeHistory 55;

答案 3 :(得分:1)

SELECT *
FROM Table
WHERE myDate >= DATEADD(MONTH, -1, GETDATE())
按月执行此操作与在30天内执行此操作不同。测试如下......

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)

结果如下:

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