日期:2014-05-16  浏览次数:20598 次

求查询连续五天大于某数值的语句
sql数据库里有两个字段名,一个是日期,一个是温度,每天一个数据记录当天的温度
现在想要得到“连续五天大于某个温度(比如大于10)的起始日期”
能否用一句sql语句实现呢
------解决方案--------------------
drop table #tmp
create table #tmp(日期 datetime,日平均温度 decimal(20,2)) 
DELETE #tmp
insert into #tmp 
select '1953-1-1',6 union all
select '1953-1-2',16 union all
select '1953-1-3',15.4 union all
select '1953-1-4',15.8 union all
select '1953-1-5',15.2 union all
select '1953-1-6',15 union all
select '1953-1-7',16.2 union all
select '1953-1-8',5.1 union all
select '1953-1-9',18.7 union all
select '1953-1-10',12.1 union all
select '1953-1-11',12.2 union all
select '1953-1-12',14.7 union all
select '1953-1-13',11.7 
 

select min([日期]) as bgdate, max([日期]) as eddate, count(1) as maxdays
from
  (select [日期], datediff(dd, '1900-01-01', a.[日期]) - (select count(1) from #tmp b where [日平均温度] >= 10 and datediff(dd, b.[日期], a.[日期]) >= 0) as  maxdays
  from #tmp a
  where [日平均温度] >= 10) a
  group by maxdays
order by maxdays