统计历年数据 南京酷得软件

 1 -- =============================================
 2 -- Author:        sucsy
 3 -- Create date: 2011-7-6
 4 -- Description:    获取任意时间段平均降水量
 5 -- =============================================
 6 ALTER FUNCTION [dbo].[GetAnyTimeSectionPrecipitationAvg] 
 7 (    
 8     @startDate datetime,
 9     @endDate datetime,
10     @Stations varchar(2000)
11 )
12 RETURNS @returnTable Table (区站号 nvarchar(10not null,
13                             --站名 nvarchar(100) not null,
14                             汇总值 decimal(18,3not null,
15                             年度 int
16 AS
17 begin
18 declare @tempTable Table (区站号 nvarchar(10not null,
19                             --站名 nvarchar(100) not null,
20                             汇总值 decimal(18,3not null,
21                             统计日期 date)                    
22 
23 
24 declare @deffYear int                                --年代数
25 declare @deffMonth int                                --统计月数
26 declare @deffDay int                                --统计日数
27 declare @tempStartDate date                            --当前计算开始日期
28 declare @tempEndDate date                            --当前计算结束日期
29 declare @currentYear int                            --当前年份递增变量
30 
31 --设置初始递增年份
32 set @currentYear = 0
33 --设置统计年代数
34 set @deffYear = YEAR(@endDate- YEAR(@startDate)
35 set @deffDay = DAY(@endDate- DAY(@startDate)
36 --设置单年统计月数
37 if MONTH(@startDate)<=MONTH(@endDate)
38     set @deffMonth = MONTH(@endDate- MONTH(@startDate)
39 else
40     begin
41         set @deffMonth = MONTH(@endDate+ MONTH(@startDate- 12
42         set @deffYear=@deffYear-1
43     end
44 
45 --遍历统计年代    
46 while @currentYear<=@deffYear
47 begin         
48     --设置当前计算开始日期
49     set  @tempStartDate=dateadd(YYYY,@currentYear,CONVERT(DATETIME,@startDate)) 
50     --设置当前计算结束日期                                                  
51     set  @tempEndDate=dateadd(MM,@deffMonth,CONVERT(DATETIME,@tempStartDate))
52     
53     set @tempEndDate=dateadd(dd,@deffDay,CONVERT(DATETIME,@tempEndDate))
54 
55     insert into @returnTable                
56     Select 区站号,SUM(汇总值)*0.1,YEAR(@tempStartDatefrom [降水历史资料库].dbo.降水日数据汇总表  where 
57            年=YEAR(@tempStartDate)          
58            and 汇总指标编码='R_Day'
59            and  统计日期>=@tempStartDate 
60            and 统计日期 <=@tempEndDate           
61            and 汇总值<30000
62            group by 区站号
63        --设置当前年份递增变量
64     set @currentYear = @currentYear    + 1                            
65 end
66 RETURN
67 end

南京酷得软件

公司网站: http://www.codersoft.cn 专业开发: 气象软件、监狱网上购物系统、两法衔接平台
原文地址:https://www.cnblogs.com/sucsy/p/2191820.html