如何在SQL Server中获取从今天午夜到昨天午夜的数据



我正在尝试获取从今天午夜到昨天午夜的日期范围。我只是关注了这个链接,但它抱怨date_trunc不支持内置功能。

我也试过这种方法,但似乎不正确。

where [startTime] <= Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()))
AND [startTime] >= Convert(DateTime, DATEDIFF(DAY, 0, GETDATE()-1))

I认为您所要求的是在清晨运行报告时获取昨天数据的方法。(你提到的午夜有点令人困惑(。

这是一个非常常见的问题,可以通过首先将要比较的值转换为日期,然后正确使用>=(大于等于(和<(小于(来轻松解决。

我为日期时间@Now1使用了一个变量,以便对其进行更改以进行测试。但在实际查询中,您可以替换getdate()

declare @Now datetime2(0) = '2021-07-16 01:00:00.000';
-- Lets see what the values are
select @Now, cast(@Now as date), dateadd(day, -1, cast(@Now as date));
-- Lets use them in a query
select *
from #Test
-- Where the CreatedDate is "greater than or equal to" the start of yesterday
-- Casting @Now to a date gives the start of today, therefore -1 days gives the start of yesterday
where CreatedDate >= dateadd(day, -1, cast(@Now as date));
-- And CreatedDate is "less than" the start of today
and CreatedDate < cast(@Now as date)

顺便说一句,我永远不会使用GETDATE()-1,因为1代表什么并不明显。最好还是坚持DATEADD()的功能,并且要有把握。

where [startTime] > CAST(GETDATE() AS DATE)
AND [startTime] < CAST(GETDATE()+1 AS DATE)

或者更简单但在大量数据上更慢

where cast([startTime] as date)=CAST(GETDATE() AS DATE) 

最新更新