我需要在7天前的午夜过后1小时提取细节。但是我没有得到我需要的结果。
我的代码:
SELECT *
FROM Table
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, getdate()))) --@StartDate
AND BusinessDay <= DateAdd(HOUR, 1, getdate()) --@EndDate
当我给出如下的实际时间时,我得到了我需要的结果:
WHERE BusinessDay >= '2018-04-04 00:01:000' --@StartDate
AND BusinessDay <= '2018-04-11 00:01:000' --@EndDate
我需要在SSRS中的参数中传递日期。但显然,SSRS中的语法也是错误的。
我尝试了以下代码,但收到错误消息:
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, CAST(getdate() as date)))) --@StartDate
AND BusinessDay <= DateAdd(HOUR, 1, CAST(getdate() as date)) --@EndDate
错误消息:数据类型日期的日期函数dateadd不支持datepart小时。
所以,我也试过下面的代码,但没有结果:
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, CAST(CAST(GETDATE() AS DATE) AS DATETIME)))) --@StartDate
AND BusinessDay <= DateAdd(HOUR, 1, CAST(CAST(GETDATE() AS DATE) AS DATETIME)) --@EndDate
答案 0 :(得分:0)
getdate()
有一个时间组件。所以,先删除它:
WHERE BusinessDay >= DateAdd(HOUR, 1, (DateAdd(DAY, -7, cast(CAST(getdate() as date) as datetime)))) AND --@StartDate
BusinessDay <= DateAdd(HOUR, 1, cast(CAST(getdate() as date) as datetime)) --@EndDate
答案 1 :(得分:0)
试试这个:
SELECT DATEADD(HH, 1, FORMAT(DATEADD(DD, -7, CAST(GETDATE() AS DATE)), N'yyyy-MM-dd HH:00:000'))
SQL Server 2014引入了FORMAT()函数,使您可以更轻松地以所需格式返回/显示数据类型,而无需使用公式进行大量数学运算。注意:格式模式区分大小写。
GETDATE() = '2018-04-11 18:20:00.000'
Formula Result: '2018-04-04 01:00:00.000'
有关FORMAT()函数的更多信息,请参见此处:https://docs.microsoft.com/en-us/sql/t-sql/functions/format-transact-sql
答案 2 :(得分:0)
稍微调整一下Gordon的答案,以避免在DATEADD函数中执行CAST时产生的错误:
DECLARE @td DATETIME = CAST (GETDATE() AS DATE);
DECLARE @td1AM DATETIME = DATEADD(HOUR, 1, @td);
DECLARE @weekAgo1AM DATETIME = DATEADD(DAY, -7, @td1AM);
然后用这个查询:
SELECT *
FROM Table
WHERE BusinessDay >= @weekAgo1Am -- @StartDate
AND BusinessDay <= @td1AM -- @EndDate
对于SSRS,请通过评论中链接的答案使用TODAY():
DECLARE @td DATETIME = TODAY();
DECLARE @td1AM DATETIME = DATEADD(HOUR, 1, @td);
DECLARE @weekAgo1AM DATETIME = DATEADD(DAY, -7, @td1AM);
同样的问题:
SELECT *
FROM Table
WHERE BusinessDay >= @weekAgo1Am -- @StartDate
AND BusinessDay <= @td1AM -- @EndDate