表结构:unit_code state_code state_change_date
K1 S01 2009-11-11
K1 S01 2009-11-11
K1 S02 2009-11-12
K1 S01 2009-11-12
K1 S01 2009-11-12
K1 S03 2009-11-13
K1 S01 2009-11-14
K1 S01 2009-11-14
K1 S02 2009-11-14
求:K1从状态S01点到非S01状态点,所有的状态S01点到非S01状态点之间的时间和。
K1 S01 2009-11-11
K1 S01 2009-11-11
K1 S02 2009-11-12
K1 S01 2009-11-12
K1 S01 2009-11-12
K1 S03 2009-11-13
K1 S01 2009-11-14
K1 S01 2009-11-14
K1 S02 2009-11-14
求:K1从状态S01点到非S01状态点,所有的状态S01点到非S01状态点之间的时间和。
SQL> with tt as(
2 select 'K1' unit_code ,'S01' state_code,'2009-11-11' state_change_date from dual
3 union all select 'K1','S01','2009-11-11' from dual
4 union all select 'K1','S02','2009-11-12' from dual
5 union all select 'K1','S01','2009-11-12' from dual
6 union all select 'K1','S01','2009-11-12' from dual
7 union all select 'K1','S03','2009-11-13' from dual
8 union all select 'K1','S01','2009-11-14' from dual
9 union all select 'K1','S01','2009-11-14' from dual
10 union all select 'K1','S02','2009-11-14' from dual
11 )select sum(to_date(b.state_change_date,'yyyy-mm-dd')-to_date(a.state_change_date,'yyyy-mm-dd'))||'天' 时间总和 from tt a,tt b
12 where a.state_code = 'S01' and a.unit_code ='K1'
13 and b.state_code<>'S01' and b.unit_code='K1'
14 and to_date(b.state_change_date,'yyyy-mm-dd')- to_date(a.state_change_date,'yyyy-mm-dd')>=0;
时间总和
------------------------------------------
18天
用connect with 函数
大家有很好的方法吗?谢谢。
S01
S02
----------第一个时间段
S02
S03
-----------此变化,无S01状态
S01
S01
S02
-----------第二个时间段
S01
-----------第二个时间段
大家有很好的方法吗?谢谢。修改一下
S01
S02
----------第一个时间段
S02
S03
-----------此变化,无S01状态
S01
S01
S02
-----------第二个时间段
S01
-----------第三个时间段