您好我一直在尝试将SQL查询从昨晚20:00提取到今天上午8点
然而,我只有20:00到24之间选择,因为它只选择昨晚哪种方式可以获得我想要的结果?SELECT COUNT(CardID) AS CardCOUNT
FROM ReaderData
WHERE (controllerID = 28) AND (ReaderTime BETWEEN '20:00:00' AND '08:00:00') AND (CardID = 'fffffff0') AND (DATEDIFF(DAY, DATEADD(DAY, - 1,
CURRENT_TIMESTAMP), dtReading) = 0)
答案 0 :(得分:0)
您已将时间与日期分开,因此您必须检查昨天的一个时间间隔和今天的另一个时间间隔。
如果您使用的是SQL Server 2008并且仅在dtReading
中存储了日期部分,则可以使用类似的内容。
select count(R.CardID) as CardCount
from ReaderData as R
where controllerID = 28 and
(
(
R.dtReading = cast(dateadd(day, -1, getdate()) as date) and
R.ReaderTime >= '20:00:00'
) or
(
R.dtReading = cast(getdate() as date) and
R.ReaderTime < '08:00:00'
)
)
<强>更新强>
时间值dtReading
更容易
通过转换为getdate()
从date
移除时间部分,然后添加您想要创建要比较的datetime
值的小时数。
select count(R.CardID) as CardCount
from ReaderData as R
where controllerID = 28 and
R.dtReading >= dateadd(hour, 20, dateadd(day, -1, cast(cast(getdate() as date) as datetime))) and
R.dtReading < dateadd(hour, 8, cast(cast(getdate() as date) as datetime))