使用此日期格式:mm/dd/yyyy h:m AM/PM
(例如:06/05/2014 5:00 PM
),如何忽略实际日期并获取特定时间之间的数据计数? (例如,下午5点至晚上9点)
我尝试了类似的东西,但当然它没有用,我不确定SQL是否可以这样做:
SELECT COUNT(id) FROM mobile_statistics WHERE timestamp BETWEEN '5:00 PM' AND '9:00 PM';
注意:时间戳字段的类型为nvarchar(MAX)
答案 0 :(得分:3)
将日期时间转换为time
:
SELECT COUNT(id)
FROM mobile_statistics
WHERE CAST(timestamp AS time) BETWEEN '5:00 PM' AND '9:00 PM';
答案 1 :(得分:1)
如上所述,只需使用convert()
将字符串转换为time
数据类型即可。然后,您可以使用判别函数来计算存储桶中的内容。像
select within_business_hours = sum(case when convert(time,timestamp)) between '17:00' and '21:00' then 1 else 0 end ) ,
outside_business_hours = sum(case when convert(time,timestamp)) not between '17:00' and '21:00' then 1 else 0 end ) ,
null_values = sum(case when timestamp is null then 1 else 0 end ) ,
from dbo.mobile_statistics ms
应该给你
null
时间戳其总和应与总行数相匹配。