当前位置: 代码迷 >> Sql Server >> 怎么查询记录中的临界点的记录
  详细解决方案

怎么查询记录中的临界点的记录

热度:6   发布时间:2016-04-24 10:36:48.0
如何查询记录中的临界点的记录
表是个流水的记录,假设每5秒记录一次当前的温度 ,如下:

TimePoint                    TempValue    PF
20131201080100       20.02              0.2      
20131201080105       27.33              1.2 
20131201080110       31.36              1.4
20131201080115       32.00              1.8
20131201080120       28.59              0.2 
20131201080125       50.26              1.4
20131201080130       20.34              1.6
20131201080135       40.18              1.5
20131201080140       35.00              1.0  
20131201080145       20.21              0.2
20131201080150       20.54              0.2
20131201080155       31.22              0.9 

得到数据  
20131201080100       20.02   关
20131201080110       31.36   开
20131201080120       28.59   关
20131201080135       40.18   开
20131201080145       20.21   关 

中间隔多少条记录不一定,就是要看那个临界的记录,根据 后面两个列进行判断,
TempValue 在 30.00-50.00 之间 并且 PF 在 1.0-2.0之间 

这种查询,因个人水平问题,除了循环判断,没有太好的想法,求大神指点。

附上测试代码


with tb(TimePoint,TempValue,PF)as(
select 20131201080100,20.02,0.2 union 
select 20131201080105,27.33,1.2 union
select 20131201080110,31.36,1.4 union
select 20131201080115,32.00,1.8 union
select 20131201080120,28.59,0.2 union
select 20131201080125,50.26,1.4 union
select 20131201080130,20.34,1.6 union
select 20131201080135,40.18,1.5 union
select 20131201080140,35.00,1.0 union
select 20131201080145,20.21,0.2 union
select 20131201080150,20.54,0.2 union
select 20131201080155,31.22,0.9 )
select * from tb

------解决方案--------------------
if object_id('tempdb..#a') is not null drop table #a

create table #a (TimePoint varchar(50),TempValue float,PF float)
insert into #a
select 20131201080100,20.02,0.2 union 
select 20131201080105,27.33,1.2 union
select 20131201080110,31.36,1.4 union
select 20131201080115,32.00,1.8 union
select 20131201080120,28.59,0.2 union
select 20131201080125,50.26,1.4 union
select 20131201080130,20.34,1.6 union
select 20131201080135,40.18,1.5 union
select 20131201080140,35.00,1.0 union
select 20131201080145,20.21,0.2 union
select 20131201080150,20.54,0.2 union
select 20131201080155,31.22,0.9 
--   select * from #a
---开始查询
;with cte as(
select  * , row_number() over (order by getdate()) num,
ison=(case when TempValue between 30.00 and 50.00 and PF between 1.0 and 2.0  then 2 else 1 end)
 from #a) 
 select TimePoint,TempValue,ison=case when ison=1 then '关' else '开' end  from cte a where 
not exists(select 1 from cte where num=a.num-1 and ison=a.ison)

----查询结果
TimePoint                                          TempValue              ison
-------------------------------------------------- ---------------------- ----
20131201080100                                     20.02                  关
  相关解决方案