查询多个观测站点在指定年份内每年的一段时间内累计降水量,并逐站排序,查询结果类似下面

站点号    年份    累计降水量    历史排序

57461    2002      452.5            2

57461    2003      524.8            1

57461    2004      389.1            3

57476    2002      154               3

57476    2003      251.7            2

57476    2004      287.8            1

我的方法是这样的,利用游标做循环,利用函数ROW_NUMBER()取序号

SqlServer 脚本如下:

/* 创建临时表,用变量形式,这样脚本执行完毕自动销毁,不必像临时表那样检测,清空,当然这只是适合我这里*/
declare @wepTable  table(siteNumber decimal(6, 0),yearNumber char(4),rainfall decimal(15,2),sequenceNum int)

/*声明游标,这个游标对应站点的数据集, */
declare wep_cursor cursor for
select distinct v01000
from h_surf_ele where v01000 between '50000' and '60000' and v01000 in ('57461','57476')

/*声明变量 用于存放游标指向的那个站号 */
declare @wep_site decimal(6, 0);

/*打开游标,并指向第一个站点 */
open wep_cursor
fetch next from wep_cursor
into @wep_site
while @@fetch_status =0
begin

     /*查询满足所有其它条件的结果,而站点号取游标指向的那个站点。取序号事利用ROW_NUMBER()函数,将查询结果插入前面声明的临时表内  */
    insert  into @wepTable
    select v01000 as siteNumber,v04001 as yearNumber,CONVERT(decimal(15,2),sum(v13241)/10) as rainfall, ROW_NUMBER() OVER (order by(CONVERT(decimal(15,2),sum(v13241)/10)) desc) as sequenceNum
                      from h_surf_ele
                     where v01000 =@wep_site

                        and substring(ymd,5,2) >= '09' and substring(ymd,5,2) <= '09'
                        and substring(ymd,7,2) > '07' and substring(ymd,7,2) <= '25'
                        and v04001 > '2000'
                        and v04001 <= '2007'
                        and v13241 <> -999    and v13241<=20000
                        and v13241 > 0
                     group by v01000,v04001

     /*游标指向下一个站点号*/
    fetch next from wep_cursor
    into @wep_site
end

/*关闭游标*/
close wep_cursor

/*销毁游标*/
deallocate wep_cursor

/*得到查询结果*/
select siteNumber as 站号,yearNumber as 年份,rainfall as 累计降水, sequenceNum as 历史排位 from @wepTable

以上语句需一起执行,因为临时表 和站号都是存放在临时的变量里的。

 

posted on 2009-09-27 19:14  秋波渡  阅读(3570)  评论(0编辑  收藏  举报