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

请教查询各月连续无降雨最大天数的SQL语句如何写?
请教查询各月连续无降雨最大天数的SQL语句如何写?

  表a数据结构如下:
---------------------------------
 年   月  日  降雨量
2013  1  1   7.3
2013  1  2   2.8
2013  1  3   
2013  1  4   
2013  1  5   
2013  1  6   
2013  1  7   
2013  1  8   1.5
2013  1  9
2013  1  10    
2013  1  11  3.2
....
2013  1  31  2.1  
2013  2  1   3.2  
2013  2  2   4.0
....
---------------------------------
    表a的资料是逐月逐日并且连续的资料,现在我需要查询的是每个月中连续几天无降雨(即空值)的最大天数。比如说2013年1月3日~7日已经连续5天无降雨,且为2013年1月中最大的连续无降雨天数,而其他日期仅间隔1~4天无降雨,那么我需要查询出来的结果就是:
---------------------------------
  年    月  连续无降雨的最大天数
2013   1      5
--------------------------------
请问各位老大,这样的查询语句怎么写?

------解决方案--------------------

with tb(a,b,c,d)as(
select 2013,1,1,7.3 union
select 2013,1,2,2.8 union
select 2013,1,3,null union
select 2013,1,4,null union
select 2013,1,5,null union
select 2013,1,6,null union
select 2013,1,7,null union
select 2013,1,8,1.5 union
select 2013,1,9,null union
select 2013,1,10,null union
select 2013,1,11,3.2),
tc as(
select *,row_number() over(order by c) num from tb
where d is null)
select top 1 a,b,count(c-num) from tc
group by a,b,c-num
order by count(c-num) desc

------解决方案--------------------
WITH a1 (yy,mm,dd,rain) AS
(
SELECT 2013,  1,  1,   7.3 UNION all
SELECT 2013,  1,  2,   2.8 UNION all