如何获取SQL服务器从今天半夜到昨天半夜的数据

How to get data from today's midnight to yesterday's midnight in SQL Server

我正在尝试获取今天午夜到昨天午夜之间的日期范围。我刚刚关注 但它抱怨 date_trunc 不支持内置函数。

我也试过这种方法,但好像不对。

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

或在处理大量数据时更简单但速度较慢

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

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

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

我为日期时间使用了一个变量@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() 功能并确定。