27,582
社区成员




create table #tmp(日期 varchar(20),日平均温度 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
--取出连续n天大于指定温度C的时间段
declare @n int; set @n=5;
declare @C decimal(20,2); set @C=10;
WITH a1 AS
(
SELECT *,case when 日平均温度>@C then 1 else 0 end as IsOver,
ROW_NUMBER() OVER(ORDER BY CAST(日期 AS DATETIME)) re
FROM #tmp
)
,a2 AS
(
SELECT *,re-ROW_NUMBER() OVER(PARTITION BY IsOver ORDER BY re) re2
FROM a1
)
SELECT MIN(日期) StartDate,max(日期) as EndDate
FROM a2
GROUP BY re2
HAVING COUNT(*)>=@n
--测试数据
create table #tmp(日期 varchar(20),日平均温度 decimal(20,2));
insert into #tmp
select '1953-1-1',6 union all
select '1953-1-2',6 union all
select '1953-1-3',5.4 union all
select '1953-1-4',5.8 union all
select '1953-1-5',5.2 union all
select '1953-1-6',5 union all
select '1953-1-7',6.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',1.7
--取出连续n天大于指定温度C的时间段
declare @n int; set @n=4;
declare @C decimal(20,2); set @C=10;
select min("date") as StartDate,max("date") as EndDate from (
select "date",IsOver
,row_number() over (order by "date")
-row_number() over (partition by IsOver order by "date") as grp
from (
select cast(日期 as datetime) as "date"
,case when 日平均温度>@C then 1 else 0 end as IsOver
from #tmp
) as t1
) as t2
where IsOver=1
group by grp
having COUNT(*)>=@n
select a.日期 '起始日期'
from [表名] a
where not exists
(select 1 from [表名] b
where datediff(d,a.日期,b.日期)<=5 and b.温度<10)