关于时间段计算的复杂问题,请大家帮忙解决,多谢了!
比如表Tab,里有两个datetime字段,分别是开始时间和结束时间(time_b,time_e),现在我想统计一个给定的时间段内的所有时长(即time_b和time_e的时间差)这个在某个指定的时间段内存在几种情况1.time_b和time_e都在这个指定时间段内。2.time_b在指定时间段内,而time_e不在。3.time_b不在指定时间段内,而time_e在。4.time_b和time_e包含了指定的时间段。对于情况很好解决,对于情况2,如果time_e不在指定时间短内,那计算时取指定时间段的结束时间作为time_e.情况3的时候和此类似。情况4就取指定的时间短为时间短。请问如何统计出指定时间段内的时长(用分钟表示)?下面是一个标例子:Tab
id time_b time_e
----------------------------------------------------------
1 2005-9-1 01:01:09 2005-9-1 06:01:09
2 2005-9-1 02:01:09 2005-9-1 04:01:09
3 2005-9-1 03:01:09 2005-9-1 05:01:09
4 2005-9-1 03:20:09 2005-9-1 03:40:09指定时间段 2005-9-1 03:10:09 - 2005-9-1 03:50:09
比如表Tab,里有两个datetime字段,分别是开始时间和结束时间(time_b,time_e),现在我想统计一个给定的时间段内的所有时长(即time_b和time_e的时间差)这个在某个指定的时间段内存在几种情况1.time_b和time_e都在这个指定时间段内。2.time_b在指定时间段内,而time_e不在。3.time_b不在指定时间段内,而time_e在。4.time_b和time_e包含了指定的时间段。对于情况很好解决,对于情况2,如果time_e不在指定时间短内,那计算时取指定时间段的结束时间作为time_e.情况3的时候和此类似。情况4就取指定的时间短为时间短。请问如何统计出指定时间段内的时长(用分钟表示)?下面是一个标例子:Tab
id time_b time_e
----------------------------------------------------------
1 2005-9-1 01:01:09 2005-9-1 06:01:09
2 2005-9-1 02:01:09 2005-9-1 04:01:09
3 2005-9-1 03:01:09 2005-9-1 05:01:09
4 2005-9-1 03:20:09 2005-9-1 03:40:09指定时间段 2005-9-1 03:10:09 - 2005-9-1 03:50:09
--->起点在指定时间段
case when (to_date(time_b,'yyyy-mm-dd hh24:mi:ss') >=to_date(2005-9-1 03:10:09,'yyyy-mm-dd hh24:mi:ss') then
(case when to_date(time_e,'yyyy-mm-dd hh24:mi:ss') <=to_date(2005-9-1 03:50:09,'yyyy-mm-dd hh24:mi:ss') then
(to_date(time_e,'yyyy-mm-dd hh24:mi:ss')-to_date(time_b,'yyyy-mm-dd hh24:mi:ss'))*60
else
(to_date(2005-9-1 03:50:09,'yyyy-mm-dd hh24:mi:ss')-to_date(time_b,'yyyy-mm-dd hh24:mi:ss'))*60
end)
--->终点在指定时间段
else
(case when (to_date(time_b,'yyyy-mm-dd hh24:mi:ss') >=to_date(2005-9-1 03:10:09,'yyyy-mm-dd hh24:mi:ss') then
(to_date(time_e,'yyyy-mm-dd hh24:mi:ss')-to_date(time_b,'yyyy-mm-dd hh24:mi:ss'))*60
else
(to_date(time_e,'yyyy-mm-dd hh24:mi:ss')-to_date(to_date(2005-9-1 03:10:09,'yyyy-mm-dd hh24:mi:ss'))*60
end)
end from Tabel
where
--->起点在指定时间段
(to_date(time_b,'yyyy-mm-dd hh24:mi:ss') >=to_date(2005-9-1 03:10:09,'yyyy-mm-dd hh24:mi:ss')
and to_date(time_b,'yyyy-mm-dd hh24:mi:ss') <=to_date(2005-9-1 03:50:09,'yyyy-mm-dd hh24:mi:ss'))
or
--->终点在指定时间段
(to_date(time_e,'yyyy-mm-dd hh24:mi:ss') >=to_date(2005-9-1 03:10:09,'yyyy-mm-dd hh24:mi:ss')
and to_date(time_e,'yyyy-mm-dd hh24:mi:ss') <=to_date(2005-9-1 03:50:09,'yyyy-mm-dd hh24:mi:ss'))
select *,
(--->起点在指定时间段
case when ....
) as 指定时间段内的时长
from
....
试试下面的语句,如果是字符串日期则做相应转换:select (case when time_b > end_time then end_time
when time_b < start_time then start_time
else time_b end
-
case when time_e < start_time then start_time
when time_e > end_time then end_time
else time_e end)*24*60
from tab
应该还有2种情况,time_b大于指定结束时间和time_e小于指定起始时间,这2种情况都是0
------>
在where 后面限制了。