我有一个包含数千个条目的数据库,有两个日期/时间字段,我们将它们称为In和Out:
In Out
2011-06-16 13:45:11.000 2011-06-16 13:49:12.000
2011-06-16 13:51:31.000 2011-06-16 14:23:17.000
2011-06-16 14:51:54.000 2011-06-16 14:58:43.000
等等…
在输入上我有一个时间框架(timeIn和timeOut)。在输出中,我需要知道属于这个时间框架的每个记录的"In"one_answers"Out"时间之间的累积秒数。用这个图表更容易说明:
http://i150.photobucket.com/albums/s99/dc2000_bucket/sql_graph.jpg从图中取名字,我需要知道"时间间隔1(以秒为单位)"+"时间间隔2(秒)"+"时间间隔3(秒)"。如何编写这样的SQL语句?
select sum(datediff(second, [In], case when @TimeOut < [Out]
then @TimeOut
else [Out]
end))
from YourTable
where [In] between @TimeIn and @TimeOut
或者像这样,如果你想包括在@TimeIn - @TimeOut结束的间隔。
select sum(datediff(second, case when @TimeIn < [In]
then [In]
else @TimeIn
end,
case when @TimeOut < [Out]
then @TimeOut
else [Out]
end))
from YourTable
where [In] <= @TimeOut and
[Out] >= @TimeIn
SQL-Server中没有GREATEST()
或LEAST()
函数,否则会像这样:
SELECT LEAST(t.timeOut, @TimeOut) - GREATEST(t.timeIn,@TimeIn)
FROM tableX AS t
WHERE t.timeIn <= @TimeOut
AND @TimeIn <= t.timeOut
使用CASE
:
SELECT DATEDIFF( second
, CASE WHEN t.timeIn <= @TimeIn
THEN @TimeIn
ELSE t.timeIn
END
, CASE WHEN t.timeOut <= @TimeOut
THEN t.timeOut
ELSE @TimeOut
END
)
AS TimeInterval
FROM tableX AS t
WHERE t.timeIn <= @TimeOut
AND @TimeIn <= t.timeOut
ORDER BY t.timeIn