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

时间:2021-07-14 03:00:32

标签: sql sql-server tsql sql-server-2016

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

我为日期时间 @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() 函数并确保。

答案 1 :(得分:0)

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

或更简单但在大量数据上速度较慢

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