SQL - 根据时间戳选择月份的所有记录

时间:2012-09-24 00:26:58

标签: sql sql-server-2008 tsql

我有一个SQL查询,可以选择24小时内的所有记录,但是,我需要更新它以选择一个月内的所有记录(相对于记录时间戳)。因此,例如,如果我在2月份选择了任何记录,它应该返回从月份开始到月末的所有记录。

我每日查询的代码是:

SELECT  Snapshot.xId,  MAX(Snapshot.TimeStamp) AS Timestamp_Actual, 
                dateadd(dd, datediff(dd,0, MAX(Snapshot.TimeStamp)), 0) AS TimestampRange_Start,
                dateadd(MI, 1439, dateadd(dd, datediff(dd,0, MAX(Snapshot.TimeStamp)), 0)) AS TimestampRange_End
                FROM Snapshot
                GROUP BY Snapshot.xId

到目前为止我所拥有的是:

SELECT  Snapshot.xId,  MAX(Snapshot.TimeStamp) AS Timestamp_Actual, 
                dateadd(mm, datediff(mm,0, MAX(Snapshot.TimeStamp)), 0) AS TimestampRange_Start,
                dateadd(dd, 0, dateadd(mm, datediff(mm,0, MAX(Snapshot.TimeStamp)), 0)) AS TimestampRange_End
                FROM Snapshot
                GROUP BY Snapshot.xId

从上面的语句中,我可以包含一个标准的WHERE子句来检查TimestampRange_Start和TimestampRange_End的值,看看Timestamp_Actual是否介于它们之间。

1 个答案:

答案 0 :(得分:1)

SELECT Snapshot.xId, MAX(Snapshot.TimeStamp) AS Timestamp_Actual
  FROM Snapshot
 GROUP BY Snapshot.xId
HAVING MAX(Snapshot.TimeStamp) >= dateadd(mm, datediff(mm, 0, getdate()), 0)
   AND MAX(Snapshot.TimeStamp) <  dateadd(mm, 1+datediff(mm, 0, getdate()), 0)