我有一个包含两列具有datetime数据类型的表。
startDateTime | endDateTime
-----------------------------------------------------
2016/01/01 13:10:50.000 |2016/03/01 15:20:21.222
我试图从startDateTime到endDateTime从10:00:00.000到16:59:59.999范围内传递的总小数中检索上表中的输出。但它没有奏效。
答案 0 :(得分:0)
如果startDateTime和endDateTime都必须包含而不考虑日期,那么您只需要检查时间部分。
SELECT *
FROM Table
WHERE
cast(startDateTime as Time) between '10:00:00.000' and '16:59:59.999'
and
cast(endDateTime as Time) between '10:00:00.000' and '16:59:59.999'
如果只有startDateTime 或 endDateTime需要落在该范围内,那么您可以使用or
SELECT *
FROM Table
WHERE
cast(startDateTime as Time) between '10:00:00.000' and '16:59:59.999'
and
cast(endDateTime as Time) between '10:00:00.000' and '16:59:59.999'
答案 1 :(得分:0)
这听起来像是有限制的聚合。如果SQL Server具有greatest()
/ least()
函数,那就太好了。但是,唉,没有。所以:
select sum(datediff(hour,
(case when convert(time, startDateTime) < '10:00:00'
then '10:00:00'
when convert(time, startDateTime) > '17:00:00'
then '17:00:00'
else convert(time, startDateTime)
end),
(case when convert(time, endDateTime) < '10:00:00'
then '10:00:00'
when convert(time, endDateTime) > '17:00:00'
then '17:00:00'
else convert(time, endDateTime)
end)
)) as diffhours
我倾向于在几分钟内完成差异,然后在最后转换为几小时:
select sum(datediff(minute,
(case when convert(time, startDateTime) < '10:00:00'
then '10:00:00'
when convert(time, startDateTime) > '17:00:00'
then '17:00:00'
else convert(time, startDateTime)
end),
(case when convert(time, endDateTime) < '10:00:00'
then '10:00:00'
when convert(time, endDateTime) > '17:00:00'
then '17:00:00'
else convert(time, endDateTime)
end)
)) as diffminutes
然后,您将决定是否要将转换舍入或截断为小时。