日期:2014-05-17  浏览次数:20940 次

【求助】关于Oracle这种需求的查询语句不清楚怎么写
数据库表记录有:

-----------日期--------------设备状态-------------------
  2010-02-05 10:25:10 S  
  2010-02-05 10:29:55 S  
  2010-02-05 10:30:12 C  
  2010-02-05 10:31:10 C  
  2010-02-05 10:33:15 S  
  2010-02-05 10:35:20 D  
  2010-02-05 10:37:19 D  
  2010-02-05 10:39:55 D  

目前查询结果,要求:
1)按时间排序,顺序不能打乱
2)查询[设备状态]不同的记录,如果同一个状态连续多条记录,那么只取这个状态的首条,
  比如记录为【A,B,A,A,A,C,C】,那么查询的期望结果应该是【A,B,A,C】

上面模拟的数据库记录期望的查询结果应该为:
-----------日期--------------设备状态-------------------
  2010-02-05 10:25:10 S  
  2010-02-05 10:30:12 C  
  2010-02-05 10:33:15 S  
  2010-02-05 10:35:20 D  

请问Oracle的查询语句应该怎么写才可以实现?
谢谢各位!


------解决方案--------------------
SQL code

create table tabs (dt date, status char(1));

insert into tabs values(timestamp '2010-02-05 10:25:10','S');
insert into tabs values(timestamp '2010-02-05 10:29:55','S');
insert into tabs values(timestamp '2010-02-05 10:30:12','C');
insert into tabs values(timestamp '2010-02-05 10:31:10','C');
insert into tabs values(timestamp '2010-02-05 10:33:15','S');
insert into tabs values(timestamp '2010-02-05 10:35:20','D');
insert into tabs values(timestamp '2010-02-05 10:37:19','D');
insert into tabs values(timestamp '2010-02-05 10:39:55','D');

with t as(
select dt,status,row_number() over (order by status,dt)-row_number() over (order by dt,status) rid from tabs
)
select dt,status from t t1 where not exists (select * from t where rid=t1.rid and dt<t1.dt) order by dt;

drop table tabs;

/*
DT                        STATUS 
------------------------- ------ 
2010-02-05 10.25.10       S      
2010-02-05 10.30.12       C      
2010-02-05 10.33.15       S      
2010-02-05 10.35.20       D 
*/

------解决方案--------------------
--tt为你的表
select 日期 ,设备状态 from
(
select 日期,设备状态,
lag(设备状态,1) over(order by rownum) 设备状态1,
row_number() over(order by rownum) rn
from tt
)
where 设备状态1 <> 设备状态 or 设备状态1 is null;
------解决方案--------------------
探讨

--tt为你的表
select 日期 ,设备状态 from
(
select 日期,设备状态,
lag(设备状态,1) over(order by rownum) 设备状态1,
row_number() over(order by rownum) rn
from tt
)
where 设备状态1 <> 设备状态 or 设备状态1 is null;