看起来你想要类似的东西
DECLARE @StartDateTime Datetime
DECLARE @EndDateTime Datetime
SET @EndDateTime = DATEADD(hour, 7,convert(datetime,convert(date,getdate())) )
SET @StartDateTime = DATEADD(day, -1, @EndDateTime )
--Print out the variables for demonstration purposes
PRINT '@StartDateTime = '+CONVERT(nchar(19), @StartDateTime,120)
PRINT '@EndDateTime = '+CONVERT(nchar(19), @EndDateTime,120)
SELECT SUM (Production) AS Prod_Date FROM YourSchema.YourTable WHERE CreatedLocalTime >= @StartDateTime AND CreatedLocalTime < @EndDateTime
但你也可以把它看作是从它们中删除 7 小时后的所有时间
SELECT SUM (Production) AS Prod_Date
FROM YourSchema.YourTable
WHERE DATEDIFF(day,DATEADD(hour, -7, CreatedLocalTime ))) = 1
第一个版本效率更高,因为查询只需在开始时执行一次日期算术,而第二个版本涉及对每条记录执行 DATEDIFF 和 DATEADD。对于大量数据,这会变慢。
镀金解决方案是将计算列添加到您的表中
ALTER TABLE YourSchema.YourTable ADD EffectiveDate AS CONVERT(date, DATEDIFF(day,DATEADD(hour, -7, CreatedLocalTime ))))
然后在该列上创建一个索引
CREATE INDEX IX_YourTable_EffectiveDate ON YourSchema.YourTable (EffectiveDate )
所以你可以写
DECLARE @YesterDay date = DATEADD(day,-1, getdate())
SELECT SUM (Production) AS Prod_Date
FROM YourSchema.YourTable
WHERE EffectiveDate = @YesterDay