简体   繁体   English

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

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

I am trying to get the date range between today's midnight to yesterday's midnight.我试图获得今天午夜到昨天午夜之间的日期范围。 I just followed this link but it complains about date_trunc not supporting built in function.我刚刚点击了这个链接,但它抱怨date_trunc不支持内置函数。

I also tried this way but seems not correct.我也试过这种方式,但似乎不正确。

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

I think what you are asking for is a way to get yesterdays data when running a report early in the morning.认为您要求的是一种在清晨运行报告时获取昨天数据的方法。 (Your references to midnight are a bit confusing). (您对午夜的引用有点令人困惑)。

This is a very common problem, easily solved by first converting values you are comparing against to dates, and the correctly using >= (greater than and equals) and < (Less than).这是一个非常常见的问题,首先将要比较的值转换为日期,然后正确使用>= (大于和等于)和< (小于),即可轻松解决。

I've used a variable for the datetime @Now1 to allow it to be changed for testing.我为日期时间@Now1使用了一个变量,以允许对其进行更改以进行测试。 But in a real query you can substitute getdate() .但在实际查询中,您可以替换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)

As an aside I would never use GETDATE()-1 because its not obvious what the 1 represents. GETDATE()-1我永远不会使用GETDATE()-1因为它不明显1代表什么。 Better to stick to the DATEADD() function and be sure.最好坚持使用DATEADD()函数并确保。

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

or simpler but slower on large amount of data或在大量数据上更简单但速度较慢

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM