0

我有一个 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 是否介于它们之间。

4

1 回答 1

0
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)
于 2012-09-24T00:57:21.000 回答